# Question
Title: Using the Rules module, is it possible to access the fields of a referenced entity of an entity?
I've got this scheme: entity person, bundle person, entity health, bundle health. Bundle health has field energy.

Bundle person has an entity reference of type health.

In Rules data selector, I want to access to `person:health:energy`. Is that possible?

# Answer
Only, you have to add a Condition (in 'Elements') to the rule of the class "Entity has field", and then a whole bunch of the referenced fields of the entity will appear and will be available.
> 1 votes

# Answer
The "`entity_has_field`" is indeed the "clue" to answer your question.

Here is a sample of such rule (in Rules export format), which will send an eMail to the userid selected via the field `field_blog_reviewer` (= a field I added to my "Blog" content type that is defined as an entity reference to a 'user'), and this whenever a new node of content type "Blog" is saved:

```
{ "rules_notify_reviewer_about_outstanding_approval" : {
    "LABEL" : "Notify reviewer about outstanding approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_blog_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-blog-reviewer]",
          "subject" : "Blog Post waiting your approval",
          "message" : "[node:author] has submitted a new Blog post waiting your approval.\r\n\r\nYou can review it at: [node:edit-url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Should you be interested in using the above rule, just use the Rules UI to "import" it. However, before doing so, make sure to first add a field with machine name `field_blog_reviewer` to content type named `blog` (this content type gets added automatically if you enable the "Blog" module).

If you try to import it without doing this, the rules "import" will fail with some type of integrity check error (in plain English: the import is rejected if the entity doesn't exist, and/or it doesn't have a field with the exact machine name). As a workaround you may also edit the exported rule above before starting the import, to make it fit the machine names of the field and the content type you want to use it for.
> 0 votes

---
Tags: 7, entities, rules
---


title: hook_menu_alter with Organic Groups

text:
# Question
Title: hook_menu_alter with Organic Groups
I want to change the menu button on my main nav bar depending if the user is or isn't a member of a group.

I need one button to 'register' if the user isn't part of a group and **that same button** changes to 'add post' if he/she is.

I do not know what to put in the array. Do I put an IF statement similar to "Correct way to use hook\_menu\_alter"?

```
   function change_menu_menu_alter(&$items) {
     $items['/node/[nid]'] = array(
       'access callback' => 'change_menu_custom_menu_access_callback',
       'access arguments' => array(1),
       // **I don't know what goes here!!!**
     );
       return $items;
   }
   function change_menu_custom_menu_access_callback($gid) {
     return og_is_member('node', $gid);
   }

```

**EDIT**: I do not have gid in my url as I am using pathauto to use \[node:content-type\]/\[node:title\] on my URL which is why I don't think the current answer works on my website.

# Answer
This is how I solved a similar problem with the `hook_menu()` and the use of '`title callback`' and `'page callback'`

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

    $items['link'] = array(
        'title' => 'test',
        'description' => t('Just a test'),
        'title callback' => 'change_title_link',
        'title arguments' => array(1),
        'page callback' => 'go_to_place',
        'page arguments' => array(1),
        'access callback' => 'user_is_logged_in',
        'expanded' => TRUE,
        'weight' => 100,
        'menu_name' => 'main-menu',
        'options' => array('attributes' => array('class' => array('perfil-usuario'))),
        );

    return $items;
}

```

In this function you can change the link title

```
function change_title_link($gid) {
  if(og_is_member('node', $gid)) {
    return 'Post';
  }
  else {
    return 'Register';
  }
}

```

Here you can redirect to the desire url

```
function go_to_place($gid) {
  if(og_is_member('node', $gid)) {
    drupal_goto('/someplace/post');
  }
  else {
    drupal_goto('/someplace/register');
  }
}

```
> 3 votes

---
Tags: 7, routes, hooks, organic-groups
---


# Question
Title: How to use the Rules and Group modules to send a privatemsg to users of a role in a group?
I am using the module Rules with Group (not Organic groups) as well as the Privatemsg module.

I want to send an email to all users of a role that are in a group. I am able to send an email to all users of a role, but I need a Rules condition that sends it to members of a certain group.

Any Suggestions?

# Answer
> 1 votes
Have a look at Comment #2 in issue # 2603136 (from the module maintainer). Here is how it looks like (I added the bold markup in it here):

> Meaning you can already use Rules to:
>
> * Add a new Group
> * Create a new GroupMembership and save it (the equivalent of $group-\>addMember())
> * Add or remove a GroupRole from a GroupType
> * React on new GroupMembership or Group entities
> *
>
> What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.
>
> Useful Rules we may add could be:
>
> * **E-mail all members of a Group, optionally filtered by GroupRole**
> * Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"
> * Feel free to add here

As per the bold phrase above, I think the exact answer to your question is "Such Rules condition is not available ... yet".

# Plan B

However, since you're also using the Privatemsg module, you may want to have a look at the community documentation about Privatemsg-Rules Integration, especially the child page about Introduction to Privatemsg-Rules: it lists the various Rules Events, Conditions and Actions you have available.

More important in the context of this question, is what's explained in the child page "Message notification via email depending on user's role". See where I'm going ...? No? Well: if you can think of a way to assign a role that corresponds to the name of the group (so 1 role for each role), you have an alternative solution that functionally will do exactly what you want to do. Obviously, 1 role for each "group" is only manageable if you don't have dozens (or hundreds?) of groups ...

**Note**: I haven't checked it yet, but it may well be possible to use the Rules module to auto-assign such role automatically when a user gets granted access to a group (Homework for you? Or ask a new question?).

---
Tags: users, rules, emails, privatemsg, 7
---


# Question
Title: How to do some calculations using fields within a Field Collection field?
I have a Field Collection field and I'm trying to do the following:

Multiply the value in one field with the value in another field and have the result shown within a third field.

I have tried Mathfield, but it doesn't support Collection Fields.

Is it possible to do this with Computed Field? How? Or would be difficult to write a custom module to do this?

# Answer
> 0 votes
Add a Computed Field with the following code (change field\_1 and field\_2 to your actual fields):

In Computed Code (PHP)

```
$field_a = field_get_items($entity_type, $entity, 'field_1');
$field_b = field_get_items($entity_type, $entity, 'field_2');
$sum =  $field_a[0]['value'] * $field_b[0]['value'];
$entity_field[0]['value'] = $sum;

```

Display Code (PHP)

```
$display_output = $entity_field_item['value'];

```

# Answer
> 1 votes
You can do it by using Computed Field. The sentence $sum = 0; $wrapper = entity\_metadata\_wrapper($entity\_type, $entity); foreach($wrapper-\>field\_FIELDCOLLECTION as $collection) { $sum += $collection-\>field\_SUBFIELD-\>value(); } $entity\_field\[0\]\['value'\] = $sum;

---
Tags: entities
---


# Question
Title: How to deal with PHP Fatal error: Cannot unset string offsets in field.default.inc when implementing custom widget?
I have a custom auto-complete widget that I use to create a custom field that is used to create a custom content type in a custom module.

I have hook\_field\_widget\_info

```
function MODULE_field_widget_info()
{
    return array(
        "MODULE_taxonomy_autocomplete" => array(
            "label"         => t("MODULE Autocomplete term widget (tagging)"),
            "field types"   => array("taxonomy_term_reference"),
            "settings"      => array(
                "size"              => 60,
                "autocomplete_path" => "taxonomy/autocomplete",
            ),
            "behaviors"     => array(
                "multiple values"   => FIELD_CARDINALITY_UNLIMITED,
            ),
        ),
    );
}

```

I have hook\_field\_widget\_form

```
function MODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element)
{
    $tags = array();
    foreach ($items as $item)
    {
        $tags[$item["tid"]] = isset($item["taxonomy_term"]) ? $item["taxonomy_term"] : taxonomy_term_load($item["tid"]);
    }

    $element += array(
        "#type"                 => "textfield",
        "#default_value"        => taxonomy_implode_tags($tags),
        "#autocomplete_path"    => $instance["widget"]["settings"]["autocomplete_path"] . "/" . $field["field_name"],
        "#size"                 => $instance["widget"]["settings"]["size"],
        "#maxlength"            => 1024,
    );

    return $element;
}

```

I have hook\_field\_widget\_error

```
function MODULE_field_widget_error($element, $error, $form, &$form_state)
{
    form_error($element, $error["message"]);
}

```

Here I am creating the field of the content type

```
field_create_field(
    array(
        "field_name"    => "field_MODULE_tags",
        "type"          => "taxonomy_term_reference",
        "bundles"       => array(
            "node" => array(
                "CONTENT_TYPE",
            ),
        ),
        "cardinality"   => "-1",
        "settings"      => array(
            "allowed_values" => array(
                array(
                    "vocabulary" => "TAXONOMY_LIST",
                    "parent"     => 0,
                ),
            ),
        ),
    )
);

field_create_instance(
    array(
        "field_name"    => "field_MODULE_tags",
        "entity_type"   => "node",
        "label"         => "Tags",
        "description"   => "",
        "bundle"        => "CONTENT_TYPE",
        "widget"        => array(
            "weight"    => 1,
            "type"      => "MODULE_taxonomy_autocomplete",
            "settings"  => array(
                "size"              => 60,
                "autocomplete_path" => "taxonomy/autocomplete",
            ),
        ),
    )
);

```

All of this appears to work fine, the content type shows the correct field, the auto complete works great, but when I try to save a new node of the custom type, I get the following error:

```
PHP Fatal error:  Cannot unset string offsets in /modules/field/field.default.inc on line 41

```

If I look at field.default.inc file I see

```
function field_default_extract_form_values($entity_type, $entity, $field, $instance, $langcode, &$items, $form, &$form_state) {
  $path = array_merge($form['#parents'], array($field['field_name'], $langcode));
  $key_exists = NULL;
  $values = drupal_array_get_nested_value($form_state['values'], $path, $key_exists);
  if ($key_exists) {
    // Remove the 'value' of the 'add more' button.
    unset($values['add_more']);
    $items = $values;
  }
}

```

where line 41 is `unset($values['add_more']);`

If I output `$values`, I get a string where unset is expecting an array.

How can I make my value an array?

I've tried using hook\_form\_alter to add a custom submit function so I can manipulate the value but the custom submit never gets fired (which is weird).

# Answer
> 2 votes
hook\_node\_validate was how I was able to fix this issue.

```
function MODULE_node_validate($node, $form, &$form_state)
{
    foreach ($form as $field => $field_data)
    {
        $field_info    = field_info_field($field);
        $instance_info = field_info_instance("node", $field, "CONTENT_TYPE");

        // since this field returns a string when an array is required, we need to correct
        // the data here before it goes any further.
        if ($instance_info["widget"]["type"] == "MODULE_taxonomy_autocomplete")
        {
            // Recieved: string
            // Expecting: array(array("tid" => TID),)
            $tag_names = explode(",", $form_state["values"][$field][$node->language]);
            $form_state["values"][$field][$node->language] = array();
            foreach ($tag_names as $tag)
            {
                $term = taxonomy_get_term_by_name($tag, $field_info["settings"]["allowed_values"][0]["vocabulary"]);
                $term = array_shift($term);

                $form_state["values"][$field][$node->language][] = array("tid" => $term->tid);
            }
        }
    }
}

```

# Answer
> 1 votes
This error happens in `field_default_extract_form_values` which is trying to load default values from the field, therefore to make it array, you need to make sure `#default_value` is in the right format.

This error usually happens when `#default_value` is NULL, but array is expected. So you can always cast it into array something like:

```
"#default_value"        => (array)taxonomy_implode_tags($tags),

```

Below is code example for radios/checkboxes-like widget with array() and with field element validation handler as per @Scott suggestion (which seems to make the difference as well):

```
/**
 * Implements hook_field_widget_form().
 */
function foo_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $value_key = key($field['columns']);
  $has_value = isset($items[0][$value_key]);
  $required = $element['#required'];
  $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;

  switch ($instance['widget']['type']) {
    case 'foo':
      $options = array(0 => t('Foo 1'), 1 => t('Bar'));
      $properties = _options_properties($instance['widget']['type'], $multiple, $required, $has_value);
      $default_value = _options_storage_to_form($items, $options, $value_key, $properties);
      if (!$multiple) {
        // If this is a single-value field, take the first default value.
        $default_value = $default_value ? reset($default_value) : array(); // <-- default array() here.
      }
      $element += array(
        '#type' => $multiple ? 'checkboxes' : 'radios',
        '#default_value' => $default_value,
        '#options' => $options,
        '#properties' => $properties,
      );
      break;
  }

  $element += array(
    '#value_key' => $value_key,
    '#element_validate' => array('foo_field_widget_validate'),
  );

  return $element;
}

/**
 * Form element validation handler for options element.
 */
function foo_field_widget_validate($element, &$form_state) {
  if ($element['#required'] && $element['#value'] == '_none') {
    form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
  }
  // Transpose selections from field => delta to delta => field, turning
  // multiple selected options into multiple parent elements.
  $items = _options_form_to_storage($element);
  form_set_value($element, $items, $form_state);
}

```

---

In rare cases the *field.default.inc* error can be related to corrupted structure of your *form state*. This can either by caused by invalid implementation of hook\_field\_widget\_form or modifying/replacing `$form`/`$form_state` in `hook_form_alter` by reference.

---

### Debugging

Debugging of invalid form state can be challenging. This can be achieved by PHP debugger (such as XDebug) and analysing structure of `$values` in `field_default_extract_form_values()` when the error happens (which suppose to be an array, not a string).

This can also be achieved by dumping the field instance which failing, for example:

```
--- a/modules/field/field.default.inc
+++ b/modules/field/field.default.inc
@@ -37,6 +37,9 @@ function field_default_extract_form_values($entity_type, $entity, $field, $insta
   $key_exists = NULL;
   $values = drupal_array_get_nested_value($form_state['values'], $path, $key_exists);
   if ($key_exists) {
+    if (!is_array($values)) {
+      var_dump($values, $field, $instance); die();
+    }
     // Remove the 'value' of the 'add more' button.
     unset($values['add_more']);

```

Or if Devel module is present, using `dsm()` or `dd()` is more convenient. For example can use `dd($form_state['values']);` to dump the whole structure of values into the file and compare the output between working and non-working scenarios.

For example (in shell) you can try:

```
> /tmp/drupal_debug.txt # Empty Devel debug file.
# Now test the working scenario to generate the dump.
cp -v /tmp/drupal_debug.txt working.txt
> /tmp/drupal_debug.txt # Empty the file again.
# Now test non-working scenario.
cp -v /tmp/drupal_debug.txt non-working.txt
diff -u working.txt non-working.txt # Or use GUI like: diffmerge, opendiff or meld

```

---
Tags: 7, entities
---


# Question
Title: How do I sort or filter a View by proximity using Search API location?
I am trying to set up a Solr Search View with Search API Solr and Search API location, witch is sorted by proximity an can be filtered by proximity. To achieve that,

* I created an search index, which indexes a geofield as `latitude/longitude` (under admin/config/search/search\_api/index/INDEX\_NAME/fields):
* I created a View for the mentioned Search index and was able to add a proximity filter as contextual filter:
    + It is also possible to add the indexed Lat/Lon field to the field section of the View and set up a formatter showing the distance to a certain geolocation:

But there wasn't any field I could add to the sort section or the filter section of the View, that filters or sorts by proximity. What do I have to do, to filter and sort a Search API Solr View by proximity?

# Answer
> 1 votes
If you want to filter based on some user selection, you can have PHP code which gets the value and filters result based on that.

Please check this http://murtuza88.blogspot.in/2014/11/use-drupal-location-module-to-filter.html for detail steps on how to filter view based on user selection.

# Answer
> -1 votes
You're wanting to sort the results by an arbitrary (unique values not stored in the database) values (distance). As said above, the most straightforward way to do that would be with php. The Views API is documented here and leads me to think that hook\_views\_post\_execute() is the function you would need.

```
<?php
function hook_views_post_execute(&$view) {
  // If there are more than 100 results, show a message that encourages the user
  // to change the filter settings.
  // (This action could be performed later in the execution process, but not
  // earlier.)
  if ($view->total_rows > 100) {
    drupal_set_message(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }

  if ($view->name == 'job_distribution') {
    foreach ($view->result as $result) {
      // figure out the distance value
      // save it to the result array
    }
    // sort the result based on that value
    // maybe use http://php.net/manual/en/function.array-multisort.php
  }
}
?>

```

Good luck!

---
Tags: views, location, search
---


# Question
Title: Facet API - Rewrite facet items via callback function
I'm trying to rewrite the link text in an Apache Solr facet block, specifically the one to drill down by bundle/content type. By default the block displays the human readable name of the content type. I want to avoid simply editing the name as this would affect other things in the site.

So, in the block I would rather have a custom text such as 'Music Videos' rather than 'Article' from the 'article' content type.

I hoped to use the hooks created by Facet API Bonus to rewrite facet items via callback function, but am having difficulty getting the code to work.

Here is what I have, based on material from here and in the Facet API Bonus module readme:

```
function custom_module_facet_items_alter(&$build, &$settings)
 {
  if ($settings->facet == "apachesolr@solr:block:bundle") {
   {
    foreach ($build as $key => $item)
     {
      switch ($key)
      {
        case 'article':
          $build['article']['#markup'] = 'Music Videos';
          break;
      }
     }
   }
 }

```

I'm using Drupal 7.27, Facet API 7.x-1.5 and Facet API Bonus 7.x-1.1 .

Thanks in advance for any help.

# Answer
> 2 votes
1. Make sure this filter is selected for your facet(s): "Rewrite facet items via callback function" admin/config/search/apachesolr/settings \> Facets \> YOUR FACET \> configure filters \> \[x\] Rewrite facet items via callback function
2. You can verify your hook is implemented using drush and devel module:

```
drush hook facet_items_alter
Enter the number of the hook implementation you wish to view.
[0]  :  Cancel
[1]  :  my_module_name

```

If you see something similar to above, then your hook is implemented. To see the implementation code, enter a number (1 in this example).

---
Tags: 7, hooks, forms, search
---


# Question
Title: Views field rewrite onClick attribute not rendering
In a D7 instance, in Views under "Rewrite the output of this field" I have this in the textarea:

```
<a href="[field_downloads]" title="[field_downloads_1-description]" onClick="recordOutboundLink(this, 'Downloads', '[field_downloads_1-description]'); return false;">[field_downloads_1-description]</a>

```

All data is displaying except for the onClick attribute. Any ideas why?

# Answer
> 5 votes
Views rewrite uses the filter\_xss\_admin function to produce safe html. It's designed as a security measure and is in place even if the user has permissions to add PHP and unfiltered HTML in other contexts.

You can work around by using Views PHP for example. See this issue at drupal.org for discussion and more on workaround approaches.

# Answer
> 2 votes
After spending a few hours digging around, I found the code based solution. You can't add onClick attributes within the Views UI because of xss filtering.

This code can be used in a custom module.

```
// Adding custom link attributes to a views field for ajax calls.
// See around line 1330 in views_handler_field.inc.(drupal 7)

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'my_expected_view_name' && isset($view->field['my_field_name'])) {
    $attributes = array('onclick' => "alert('Hello')");
    $view->field['my_field_name']->options['alter']['link_attributes'] = $attributes;
  }
}

```

---
Tags: 7, views
---


# Question
Title: Add value to field using Entity Metadata Wrapper
I'm trying to accomplish the seemingly simple task to add a value to a multi-value file field in Drupal 7. I have been trying for hours, but none of the answers I found would solve my problem.

My field is called `field_video_ext`. Using the Remote Stream Wrapper module, I would like to add values like this (using some of the module's code):

```
<?php

// My videos and their respective nodes.
$videos = array(
  array(
    'nid' => '1903',
    'uri' => 'http://example.com/movie.flv',
  ),
  array(
    'nid' => '3172',
    'uri' => 'http://example.com/movie2.flv',
  ),
);

foreach ($videos as $video) {
  // From the Remote Stream Wrapper module.
  try {
    $file = remote_stream_wrapper_file_load_by_uri($video['uri']);
    if (!$file) {
      $file = remote_stream_wrapper_file_create_by_uri($video['uri']);
      file_save($file);
    }
  }
  catch (Exception $e) {
    drupal_set_message($e->getMessage());
  }

  if (empty($file->fid)) {
    drupal_set_message(t('Unable to add file from URL %file.', array('%file' => $video['uri'])));
    exit;
  }
  // Display needs to be set.
  $file->display = 1;

  // Get Entity Metadata Wrapper
  $wrapper = entity_metadata_wrapper('node', $video['nid']);

  // Write information into fields.
  $wrapper->field_video_ext->set(get_object_vars($file));

  // Save wrapper.
  $wrapper->save();

}

?>

```

Now the problem is that this doesn't work if the field accepts multiple values. It throws the error

> EntityMetadataWrapperException: Invalid data value given for wrapper chain

I then tried using `$wrapper->field_video_ext[] = get_object_vars($file);`, but that doesn't work either. I think it was this error I got:

> Fatal error: Cannot use object of type Project as array

I also tried the following instead of `get_object_vars($file)`:

```
$file = (array) $file;
$items = array($file);

```

And then saving that array using `set()` or the `[]` way. But to no avail. Can anybody tell me what I am doing wrong?

# Answer
One issue may be that `get_object_vars()` returns an array with keys that the file field does not understand. The EntityMetadataWrapper documentation provides two options for setting file reference values, though it appears to use single value fields in the examples:

Setting the file directly:

```
$w_containing_node->field_attachment_content->file->set( $file_obj );

```

Providing an array with just `fid`:

```
$w_containing_node->field_attachment_content->set( array('fid' => $fid) )

```

---

One of the comments provides the following examples from the entity tests which apply to a multi-value field, though I'm not sure if setting the full file object will work appending a new item:

```
$wrapper->field_file[0] = array('fid' => $file->fid, 'display' => TRUE);
$wrapper->field_file[1]->file = $file;

```
> 4 votes

---
Tags: 7, entities
---


# Question
Title: How can I create Menu items through hook_install()?
Like it was said in subject, how would I do that?

I need to create menu items once after module install and have the ability to edit them if needed.

module.link.menu.yml won't give me that ability.

Anybody have suggestions?

# Answer
You *can* use hook\_menu\_links\_discovered\_alter() to modify or add additional links to those provided in \*.menu.links.yml files, but these types of links are not completely editable (e.g. you can not change their title in the UI).

If your links are content based, need to be completely editable later through the UI, or are being placed in a custom menu you can directly create the menu link entities:

```
MenuLinkContent::create([
  'title'      => 'My internal link from a route name',
  'link'       => ['uri' => 'route:myroute'],
  'menu_name'  => 'my-menu',
])->save();

```

Also check out the Entity API documentation, and Working with the Entity API for more information.
> 2 votes

---
Tags: routes, 8, installation
---


# Question
Title: How to select by default nodes of a content type in admin/content through a link?
I'd like to make a link to `admin/content/`, but when the page was displayed I'd like to have it filtered by a certain content type.

The link can be like this `admin/content/house` so when I click it, the admin/content page is already filtered by house Content Type.

Is this possible?

Is something like this How to link to dblog filtered by type? but for the admin/content path.

**Edit:** If I click in a link that can be like this `admin/content/house` I can have in the `admin/page` the Content Types filtered by House, something like this picture

# Answer
It looks like you're making use of the Admin Views module, so you can add filter options as GET parameters in the URL: http://localhost/admin/content?type=article

You can also make a clone of the content admin view and modify it. This would allow you to set contextual filters, modify the exposed filter fields, or adjust visible columns to make a more targeted content listing.
> 5 votes

---
Tags: 7, navigation, nodes
---


# Question
Title: Is it safe to change INT to BIGINT or DECIMAL in database?
I need to change a field from INT to BIGINT or DECIMAL. I tested changing it directly in the database on `field_data` and `field_revision` tables and apparently all is working fine, but I have my doubts and I don't want to do that on production until I'm entirely sure it's safe. It's enough to change the data type on database or I have to do something else like the solutions listed in the links below? If it's not safe to just change it in database, I'd like to know why.

# Answer
> 3 votes
Usually, when you make a change of this type it is recommended to make it in a development environment, so you can make some test to check your site is working correctly.

In the case you decide to make it in a production environment, be sure you make a backup of your database, in order to restore your system in case of problems.

# Answer
> 1 votes
If you want to be safe, here is what I would do.

If you can view your Drupal database with phpmyadmin or some other package/program/tool.

Export the field in question DB table that you want to change as a CSV file.

Add your new field, then edit 1 node and add a value to that field. Export the new field (which has 1 value) as a CSV file.

Open both CSV files in excel. Copy the node id (nid) column and the field value column from the field in question CSV to the New CSV and save changes.

Import New CSV to the New Field DB Table.

Do the above again for the `_revision` version of the table.

Flush the Drupal Cache.

Delete the field in question.

---
Tags: 7, entities
---


# Question
Title: What to choose Content Type or Drupal Commerce or Ubercart
I'm working on a project where we've people managing product in site (including product creation, editing, viewing, reviewing, etc.). These are not going to be techie people so the product management should be easy to use with quick loading. The site as of now doesn't allow users to sell and buy product online (It might allow in future, but not confirmed - very less chances). Its just viewing, reviewing, rating products. Also there will be variety of product. We're also planning on creating Mobile App for this so user can manage products from App.

As I've already worked with all of these 3 earlier, my personal thought is that Drupal Commerce and Ubercart may add an extra overhead of e-commerce functionality on our site. I need suggestion on how should we proceed here, what things should we consider while selecting any one of these 3. What should be best choice to go ahead in such scenario i.e. Plain content type or Drupal Commerce or Ubercart.

# Answer
> 2 votes
Just go (start with) what you call "Plain content types".

For the "rating" requirements, have a look at my answer to "What are recommended modules or processes which support rating based comments or reviews?".

Should you ever want to expand that to a (rather basic) e-shop and/or add a shopping cart, you can always use the modules as I suggested in my answer to "How to create a simple shopping cart without Drupal Commerce or Ubercart?".

Next question?

# Answer
> 1 votes
> We're also planning on creating Mobile App for this so user can manage products from App.

I highly suggest you go with Drupal 8 as it's mobile ready and friendly.

If you are not selling anything, content types is the way to go.

For displaying various products you can use the Views module, which comes with Drupal 8.

For performance Drupal 8 automatically caches your pages and clears the cache when you make changes.

---
Tags: 7, nodes, commerce, ubercart
---


# Question
Title: What could cause the site to suddenly start dying with the "Call to undefined function entity_get_info()" error?
So I was working away at trying to solve the problem I asked about in How can I combine the fields of two field collections in my theme? when suddenly Drupal died with this error message:

> Fatal error: Call to undefined function entity\_get\_info() in /path/to/drupal/sites/all/modules/entity/includes/entity.inc on line 57

This is the call stack.

Now since it seems to die when working with the field collection module, and I was working with that field, it is obvious that something I did caused the entire site to crash, but how, and how can I recover from it? I can't clear cache to try to see if that fixes anything because drush throws the same error and I can't access the cache clear on the site itself obviously.

## What I was doing

I was working on the theme\_preprocess\_field() function and had something like this:

```
<?php
function enviroscope_preprocess_field(&$variables) {
    $roles = array();
    if ($variables['field_name_css'] == 'field-doc-staff-contrib-fc') {
        foreach ($variables['items'] as $item) {
            $role = array_values($item['entity']['field_collection_item'])[0]['field_fc_doc_iges_role'][0]['#markup'];
            $user = array_values($item['entity']['field_collection_item'])[0]['field_fc_doc_iges_user'];
            $toreplace = $user['#object']->field_fc_doc_iges_user['und'][0]['entity']->name;
            $replacewith = $user['#object']->field_fc_doc_iges_user['und'][0]['entity']->field_user_family_name['en'][0]['#safe_value']
            $roles[$role][] = $item;
        }
    }
    kpr($roles);
}

```

I started adding some scaffolding for the next step, which was to be examining the `field-doc-other-contrib-fc` field collection field.

I meant to modify the code after `kpr($roles);` to read as follows:

```
    kpr($roles);
    variable_set('roles_to_pass', $roles);
} else if ($variables['field_name_css'] == 'field-doc-other-contrib-fc') {
    $roles = variable_get('roles_to_pass', array());
    // sort and mix these together
    variable_del('roles_to_pass');
}

```

My best guess about what possibly could have happened is that I accidentally wrote `else if ($variables['field_name_css'] = 'field-doc-other-contrib-fc') {` (note the = instead of the ==) which would have reset the field\_name\_css on every field except the first field collection field I was working on. Would this explain the entire site going down in the way it has? How can I recover from it?

In the morning if there is no answer I'll try deleting all rows from the various cache\_\* tables directly in the database, but for now I need to hit the hay.

### Update

Clearing out the cache tables and commenting out my entire template.php had no effect. Is my entire install hosed?

# Answer
You have a classed `FieldCollectionItem` object in your variables table. Drupal 7 isn't designed to handle this.

When you use `variable_set()` to save an object to the variables table, the object must first be converted into a string using `serialize()`. Later, it will have to figure out how to convert that string back into a FieldCollectionItem object, and it will call the `__wakeup` magic method on the class to help it figure out how to do that. It turns out that `__wakeup` method requires code that isn't bootstrapped yet at the time that Drupal reads from the variables table, so you get the fatal error.

But you're not hosed. It looks you probably saved the object in the '`roles_to_pass`' variable. If you can edit your database, try removing that record from the `{variable}` table, then clear your cache tables.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: Command pm-enable needs a higher bootstrap level to run
I've been scouting the forums for the past two days trying to get an answer to my problem, i'm new to Drush but pretty good with Drupal. my environment is as follows:

* centos 6
* php 5.3.3
* drupal 7.x single site basic installation

I've installed `drush`, then `cd` to my site root directory and i used drush dl seo\_checklist which worked fine.

when I run `drush en seo_checklist` I get the following output:

```
Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. [error]

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

Drush was attempting to connect to:
 Drupal version         :  7.34
 Site URI               :  http://default
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /var/www/html/mytestsite
 Site path              :  sites/default

```

i did modify my settings file to include:

```
'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost'

```

**UPDATE - 1**

`drush st` returns the following:

```
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

```

everything inside the root folder has 755 permissions and belongs to apache:apache

I am running the `drush` command as root. i have no idea what could be causing the problem.

# Answer
Is your settings.php file in sites/all/default? If not, you'll need to add the --uri option. If your settings.php file is in sites/all/foo.com, then add --uri=foo.com.

`drush --uri=foo.com en seo_checklist`

Or, change your working directory to the same folder that contains settings.php.

Or, define a site alias @foo that defines 'root' and 'uri', and then use:

`drush @foo en seo_checklist`
> 5 votes

# Answer
To actually find out why this is happening so you get a better idea of how to fix it, run a drush command with the `--debug` option. eg: `drush pm-list --debug`. Then look through the output to see anything that might be causing the problem.
https://2pha.com/blog/fixing-drush-needs-higher-bootstrap-level-run
> 4 votes

# Answer
In my case it turned out that I needed to install mysql-client:

```
apt-get install mysql-client

```

I had the following situation: drush 4, 5 and 6 worked fine for me. drush 7, 8 don't work (different errors, including that ones you're describing). And my MySQL database was located on a separate server.

HTH, Alexander
> 3 votes

# Answer
I had the same problem and had to add something to $PATH by editing my .bash\_profile

```
# Add PHP to drush path export DRUSH_PHP='/Applications/MAMP/bin/php/php[your-php-version]/bin/php'

```

see Drush does not work on my Mac
> 1 votes

# Answer
Seems like you are runing drush from outside a drupal webroot folder. Ensure you are running drush from inside the folder where drupal is, anywhere within that folder drush should not give you this error
> 1 votes

# Answer
Update PHP, I had the same issue with CentOS6, replaced PHP 5.3.3 with 5.5.22 from webtactic and drush ran no problem.
> 0 votes

---
Tags: drush
---


title: website doesn't load

text:
# Question
Title: website doesn't load
I had a fully working Drupal site and had some problems with uploading files on a specific page. So I started looking closely at the code and noticed some oddities (basically a lot of random characters). I removed the code and everything seemed to be fine. The code had to do with the images on the page. Then all of a sudden I started receiving a "page cannot be displayed" error, and was not able to view the site anymore.

I had someone else look at the server and they were able to connect just fine. To be on the safe side, they rebuilt the page. I tried again, and still couldn't see the website.

I then tried to attempt the connection through another network I manage via VPN. Coming at it from the other network, the page loads. I've tried Firefox, Chrome, Safari, all with the same result. I tried clearing the cache, reset settings, delete and reinstall. I've restarted my router. I'm out of ideas. This has been super frustrating. Thanks for any help.

Update: I talked to the person hosting this and they mentioned they run something called Liquid Web. I guess it bans your IP if it thinks you're doing something bad. All I did was modify a page it banned me.

# Answer
> 3 votes
You don't go into any detail about what the page won't load means. Is there an error that is being displayed by the browser? If so what is it? In this case it is likely that you are getting some kind of http error code back from the server, or the request is timing out.

You may want to look at your server's fail2ban log. If Fail2ban is enabled, it is possible that your ip address has been blocked.

Is there an error in a web page? Do you get a blank page? If so, does viewing page source show anything?

Errors in the web page are much more likely an sign of something coming from drupal. Though http error codes could easily be coming from drupal too.

If you use the developer tools in whatever browser you are using to look at the request and response headers what do you see?

This will give you a clearer view of what is being requested and what the server is answering?

Do you see anything in your server's error log? Does anything show up in the access log? This will give you a clearer view of whether the request is reaching your web server at all. If you see no request in either the access or error logs, it is a reasonably good bet that you are being blocked at the firewall level (this includes fail2ban) or that you have some local dns setting that is causing your request to go to the wrong place. (This could be something in your /etc/hosts)

---
Tags: users
---


# Question
Title: User registration times out/doesn't exit on live centos+nginx server
I have a bit of an edge case, but it's confusing me very much. I noticed that my services `user/register.json` POST calls would just endlessly freeze on my production server, but not on my local, however it would actually successfully create the user. Also, it would happily exit with a `services_error()` callback if the user couldn't be created (existing username, for example).

On further investigation, it seems that the user registration form itself on the drupal site does the same thing. No errors come up, nothing in the logs, just an endless timeout on successful save and drupal set message errors on unsuccessful save. Even when I go into the code and insert watchdog messages, they only actually get pushed through on the next successful request. It also only seems to be registration that is affected, and creating a new user from the admin interface is completely fine.

The production server is a CentOS 7 box running nginx with php-fpm, mariadb & memcached, seems to have enough memory, doesn't appear to have any weird low timeout values in the settings, etc.

Can always provide any conf files or anything if that helps, but I was wondering if anyone knew of any known issues where only user registration could be affected. Thanks in advance!

# Answer
Issue was a faulty mail server. For some reason when it couldn't use mimemail properly it was choking without error, kinda annoying. Fixed by setting up a proper external mail transactor (mailjet module in my case).
> 0 votes

---
Tags: 7
---


title: Drupal commerce custom discount

text:
# Question
Title: Drupal commerce custom discount
I'm using the Drupal Commerce module.

I want to make a discount rule where if there are 3 or more products of type X, you get a discount of 40% on all type X products. I don't know how I can do this without affecting type Y. Can this be done by pricing rules?

# Answer
If you're willing to make "products of type X" "products with taxonomy term X" instead, you could probably get away with using Commerce Taxonomy Conditions. With it, you can create a product discount that applies 1) if an order has a certain quantity of a taxonomy and 2) if the current product has a certain taxonomy term.

If that didn't suite you, you could model the correct discount/inline conditions from that code... ripping out the taxonomy bits and replacing them with Drupal Commerce product types.
> 2 votes

# Answer
Solved it! I used pricing rules to look for the right SKU and then checked how many of these SKU's there are in the basket

Aantal=Amount

I also added a rule for \<3 items.
> 1 votes

---
Tags: commerce
---


title: image system help

text:
# Question
Title: image system help
New to Drupal, but am finding it pretty amazing.

I have imported over 4000 articles from another site. At the moment, I have 'filtered hmtl' switched on for all of these articles.

They have html image code (the images are posted in from an external source)

It looks like this:

```
<img width="350" align="left" src="http://***********" alt="" />

```

I am very happy with the way the image system in Drupal 7 works, but supposing I wanted to apply a style (border, padding etc) to these images, and therefore switch html on the 'full' what's the best way to go about it?

I don;t want to do anything that would interfere with the core image system.

Any help would be much appreciated.

# Answer
> 0 votes
You can use javascript to look for img tag and attach your class, once you attached the class then use CSS to apply border padding and etc.

Code for adding Class:

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
</script>
<script>
$(document).ready(function() {
     $( "img" ).addClass( "classname" );
}
</script>

```

Where to add this code ?

I will suggest to add this into your content type tpl.php file.

If you don't already have one, create one.

in your theme folder create a new file name it **node--articles.tpl.php**

and past the code into that file.

```
<?php

/**
 * @file
 * Default theme implementation to display a node.
 *

?>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
    </script>
    <script>
    $(document).ready(function() {
         $( "img" ).addClass( "classname" );
    }
    </script>

```

**Please note: In node--articles.tpl.php, rename the articles to your content type machine name.**

Now you can go to your css file and start playing with your class name.

```
.classname {

}

```

**How the code work ?**

When article page is clicked, the javescript code look for img tag and attach the class name into it.

---
Tags: 7, media
---


# Question
Title: How can I perform an operation programatically when the value of a user field is changed?
On my user accounts, I have a text field, `field_nickname`. Users can change this at any time.

When they do change it, however, when the user account is saved I want to copy the old value for `field_nickname` to a text field accepting unlimited values, `field_nicknamehistory`.

In Drupal 7, you could do this in Rules by making a rule "on user update" and accessing the old value through the tokens in the rule interface. However, Rules isn't here yet for Drupal 8, so I'm trying to do this in code.

I tried to do this with `hook_user_presave()` but I don't know how to get the old value to compare it against the new value:

```
function mymodule_user_presave(Drupal\user\UserInterface $entity) {
  // How do I get $previousnickname?
  if ($entity->get("field_nickname") !== $previousnickname) {
    $entity->get('field_nicknamehistory')->appendItem($entity->get($previousnickname));
  }

```

I looked through the API and found onChange(), but I don't see how that would help me here.

# Answer
> 3 votes
The Content translation module has code you could use, right in its `hook_entity_presave()` implementation (i.e. `content_translation_entity_presave()`).

```
if (!isset($entity->original)) {
  $entity->original = entity_load_unchanged($entity->entityType(), $entity->id());
}

```

In `$entity->original` you then find all the values that entity object had before being changed, as the documentation for `entity_load_unchanged()` says:

> Loads the unchanged, i.e. not modified, entity from the database.
>
> Unlike `entity_load()` this function ensures the entity is directly loaded from the database, thus bypassing any static cache. In particular, **this function is useful to determine changes** by comparing the entity being saved to the stored entity.

If you want to write code that will need less changes when passing to Drupal 9, you can use the following one, which replaces the call to `entity_load_unchanged()` (marked *deprecated*) with that function's code.

```
if (!isset($entity->original)) {
  $entity->original = \Drupal::entityManager()->getStorage($entity->entityType())->loadUnchanged($entity->id());
}

```

Also `image_entity_presave()` uses `$entity->original`, but it doesn't load it if it has not been set.

```
$original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;

```

Probably, you could simplify the code.

```
if (!isset($entity->original)) {
  // Get the old value of the field.
}

```

Looking at the method calling `hook_entity_presave()`, `EntityStorageBase::doPreSave()`, the latter seems a more correct code.

```
  $id = $entity->id();

  // Track the original ID.
  if ($entity->getOriginalId() !== NULL) {
    $id = $entity->getOriginalId();
  }

  // Track if this entity exists already.
  $id_exists = $this->has($id, $entity);

  // Omissis

  // Load the original entity, if any.
  if ($id_exists && !isset($entity->original)) {
    $entity->original = $this->loadUnchanged($id);
  }

  // Allow code to run before saving.
  $entity->preSave($this);
  $this->invokeHook('presave', $entity);

```

`EntityStorageBase::doPreSave()` already sets `$entity->original` for entities that aren't new; the code used from `content_translation_entity_presave()` seems excessive.

# Answer
> 0 votes
Based on @kiamlaluno's answer, here is the code that worked for me (note that it adds a timestamp when recording the change to the field):

```
function mymodule_user_presave(Drupal\user\UserInterface $entity) {
  if (!$entity->isNew() && ($entity->get('field_nickname')->value !== ($entity->original->get('field_nickname')->value))) {
    $record = $entity->original->get('field_nickname')->value.' '.date('Y-m-d H:i:s');
    $entity->get('field_nicknamehistory')->appendItem($record);
  }
}

```

---
Tags: hooks, 8
---


title: Multiple Indexes with Apache Solr

text:
# Question
Title: Multiple Indexes with Apache Solr
Is it possible to use multiple indexes with Apache Solr? We want to use different indexes depending on the environment id.

# Answer
Setup multiple solr core's and then use settings.php to define for each environment as poster above said.

If you are using ApacheSolr its like:

```
$conf['apachesolr_environments']['my_env_id']['url'] = 'http://localhost:8983';

```

Just make sure your settings.php is not moved from server to server, if it is then use environment variable in apache:

```
SetEnv ENVIRONMENT development
SetEnv ENVIRONMENT staging
SetEnv ENVIRONMENT production

```

And use something like this in settings.php

```
<?php
switch ($_SERVER['ENVIRONMENT']) {
  case 'development':
    $conf['apachesolr_environments']['my_env_id']['url'] = 'http://localhost:8983';
    break;
  case 'production':
    $conf['apachesolr_environments']['my_env_id']['url'] = 'http://www.domain.com:8983';
    break;
}
?>

```
> 1 votes

# Answer
Yes. One way to do this \[on a single Solr server\] use Multi-core Solr, and have an index for each environment (Dev, Staging/Test, Prod/Live).

You'll probably want to customize the index file per environment based through some flag you'd set in `settings.php` (per environment); there are utility modules that help split settings amongst each env.
> 0 votes

---
Tags: search
---


# Question
Title: How to remove Quicktabs cookie on certain page?
I found a useful snippet here to make Quicktabs remember which tab was open if the user leaves the page and then comes back again. My problem is that I want to remove the history (the cookie) after the user has payed a visit to a certain page. In that case I want the default tab to be opened when the user comes back again. In the Quicktabs settings I have set the wanted default tab.

I have a script.js in my theme with this snippet:

```
  Drupal.behaviors.quicktabsHistory = {
    attach: function(context, settings) {
        var id = $(this).attr('id');
        var tab = $.cookie(id);

        // enable quicktabs memory
        $('.quicktabs-wrapper', context).each(function() {
            if (tab != '') {
              $(this).find('ul.quicktabs-tabs a#' + tab).click();
            }
            $(this).find('ul.quicktabs-tabs a').click(function() {
                $.cookie(id, $(this).attr('id'));
            });
        });

        $('.view-taxonomy-term', context).each(function() {
            if (tab != '') {
              $.removeCookie('id');
            }
        });
    }
};

```

Everything works fine, except for the part where I want to loose the history. How can I remove the cookie if the user visits the page with the wrapper class ".views-taxonomy-term"?

EDITED: I tried changing the removeCookie row to insteaed force the tab I want to be the default one:

```
    $('.view-taxonomy-term', context).each(function() {
        if (tab != '') {
          tab = 'quicktabs-tab-instrument_flikar-0';
        }
    });

```

But that did not do the trick. I have checked though with a breaking point in the script that the tab variable actually is set to the new value, but the previous tab is still activated after return to the page with the tabs. There is something about Drupal.behaviors.quicktabsHistory that I don't understand, obviuosly. :-(

# Answer
Finally solved it. In case anyone is stuck with the same problem, this code now works for me. I learned that it's important to always set the path, to be able to retrieve the same cookie on different pages. I never got $.removeCookie() to work, so instead I used a default value. Also it did not work to use true, false and undefined as values, but it worked to use them as text inside quotes, 'true', 'false' and 'undefined'. Slowly getting there :-).

```
      Drupal.behaviors.quicktabsHistory = {
        attach: function(context, settings) {

        var default_tab = 'quicktabs-tab-instrument_flikar-0';
        if($.cookie('id', {path:'/'}) == 'undefined'){
            var id = $(this).attr('id');
        }else{
            var id = $.cookie('id', {path:'/'});
        }
        var tab = id;
        var flagga = $.cookie('flagga', {path:'/'});

        if($("body").is(".page-taxonomy")) {
            $.cookie('flagga', true, {path:'/'});
            $.cookie('id', default_tab, {path:'/'});
        }

        $('.quicktabs-wrapper', context).each(function() {
            if (tab != '' && flagga === 'false') {
              $(this).find('ul.quicktabs-tabs a#' + tab).click();
            }
            else {
              $.cookie('flagga', false, {path:'/'});
              $(this).find('ul.quicktabs-tabs a#' + default_tab).click();
            }

            $(this).find('ul.quicktabs-tabs a').click(function() {
                $.cookie('id', $(this).attr('id'), {path:'/'});
            });
        });
    };

```
> 0 votes

---
Tags: javascript, blocks
---


title: Why don't I get any CSS output?

text:
# Question
Title: Why don't I get any CSS output?
I did a fresh install of Drupal 8. Everything had a nice style while installing, but when it was done, there was no CSS anymore. Did the installation change some file rights?

* I tried flushing the cache
* I did check if the core/theme folder has CSS files in it
* I did a re-install, but again there is just raw HTML

I checked and it looks like I have an HTTP/1.1 500 Internal Server Error on all CSS and JavaScript files.

Update: The issue is with the .htaccess file in /sites/default/files/.htaccess I changed the permission of the file to 644, then once changed, i did edit the file via the file manager and commented out these lines:

#Options -Indexes -ExecCGI -Includes -MultiViews php\_flag engine off

It works now but is tis a safe way to do it?

# Answer
In my case, I was getting this in the apache error log:

```
.../sites/default/files/.htaccess: Option MultiViews not allowed here

```

Checking `.htaccess`, I found:

```
# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

```

Even though it's turning `MultiViews` off, it's still not allowed, and removing it fixed the CSS. Enabling sites to set it int he global apache config would also resolve it.
> 1 votes

---
Tags: 8, theming, .htaccess
---


# Question
Title: How to style/theme an openlayers map block?
I can't seem to figure out how to target the block that my OpenLayers map sits in. I've switched from a Gmap to an OpenLayers implementation, so I already know which styles I want to apply to the Map block itself, but when I mess with the styles in chromes dev tools I get strange results such that my points and map controls get moved, but not the map container itself

So applying the styling to the map block directly in dev tools result in the base-layer being pushed off and inaccurate. It looks like the map block and div id's get generated by the javascript in openlayers on each page load, so I'm not sure exactly how or where to apply my CSS. I get similar results when I target the map container div as well.

This the css I was applying to the Gmap

```
#block-views-phi-rho-chapter-map-block-1 {
  width: 95%;
  margin-left: auto;
  margin-right: auto;
}
@media all and (min-width: 720px) {
  #block-views-phi-rho-chapter-map-block-1 {
    width: 85%;
  }
}
    .view-phi-rho-chapter-map {
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  border: 10px solid #dbdbdb;
}

```

# Answer
ok, so the answer should have been more obvious to me but I'm not really a front-end guy so it took a little head scratching to see that I just had to target the block by class rather than id...
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: How to display a default value for minute field of Time fieldtype
I have a **Time** component in my webform. When I go to my form I see **Hour** is selected by default in the **Hour** field but I see **00** is selected by default in the **Minute** field.

How I can set **Minute** as the default value in the **Minute** field?

# Answer
> 1 votes
As the time component says in its description field, it "accepts a time in any GNU Date Input Format. Strings such as now, +2 hours, and 10:30pm are all valid."

If you want to set the default minute, you can used a formatted string like "1972-09-24T20:02:00,000000-0500" or "10:30pm" in the **Default value** field.

# Answer
> 0 votes
I believe this is due to a bug I just reported here: https://www.drupal.org/node/2663960

Try to modify the following file: sites/all/modules/webform/components/time.inc by looking for:

```
$default_values = array(
  'hour' => '',
  'minute' => '0',
  'second' => '',
);

```

(line 191) and change it to:

```
$default_values = array(
  'hour' => '',
  'minute' => '',
  'second' => '',
);

```

Keep your eye on the link I posted above to see the official resolution of this issue.

---
Tags: entities, webforms
---


# Question
Title: How do I customize the flag/unflag links?
I'm fairly new to Drupal theming, and I am trying to customize the HTML output the Flag module for Drupal 8 produces for flag/unflag links; more specifically, I would like to make the links appear as buttons using Bootstrap classes. Does anyone know a good way to do this? I'm placing the flag link on the user profile page to enable users to follow other users. Here are some approaches which I have tried, so far without success:

* Using the Twig `replace` filter to modify the output. This does not work, apparently because a "lazy builder" is used, delaying the production of the actual HTML output until a later stage after Twig's rendering is already complete.
* Overriding the `flag.tpl.php` template with a customized version. This has no effect; maybe this functionality is no longer active in Drupal 8 (which did away with PHP templates in general)?
* Using `flag_create_link` in a theme preprocess function. I got an error that this function does not exist; maybe it no longer exists in the Drupal 8 version of the module? (or else maybe I'm missing a necessary import).

# Answer
This works in D7, but I am sure it transfers to D8.

**One approach is to use Views**

1. Under Advanced, RELANTIONSHIP add a relationship of flag, in order to get access to the flag link field.
2. In FIELDS, add **flag link field**, and under Style Settings \>\> Checkmark customize field HTML \>\> Select DIV \>\> type your bootstrap class name.

In your theme's css file add this, ex:

```
.ddd .flag-action { border: solid green; }
.ddd .flag.unflag-action { border: solid red;  }

```
> 1 votes

# Answer
Here is a solution that ended up working for me. In my MYTHEME.theme file, I put the following:

```
function MYTHEME_preprocess_user(&$vars){
  $f = \Drupal::service('flag.link_builder');
  $link = $f->build('user',$vars['user']->id(),'followed');
  $link['link']['#attributes']['class'][]="btn";
  $vars['follow_link'] = $link;
}

```

Then, in the `user.html.twig` template, I put `{{ follow_link }}` in the appropriate place. It's not a perfect solution, though, because it is not compatible with AJAX links (in which case the button styling is lost after the button is clicked). But with normal links, it works.
> 2 votes

# Answer
From what I could discover, the flag links are just link render elements, which can be modified by `hook_link_alter()`.

The following code is not actually tested, (and may break in the future)

```
function MYMODULE_link_alter(&$variables) {
  if (strpos($variables['options']['attributes']['id'], 'flag-') === 0) {
    $variables['options']['attributes']['class'] += [
      'new-class',
    ];
  }
}

```

---

I hope that there is a better approach possible, but they only other alternative I could find was swapping out the `flag.link_builder` service to apply your desired classes instead of relying on the alter hook.
> 1 votes

---
Tags: 8, flags
---


# Question
Title: Add option values to field that already has data
I created a content type with a field "Category".

In that field I added two values: \- Books \- Movies

I inserted data in this content type and I have a view showing the content per category. Now i need to add a new value "Series" but it shows this message:

**There is data for this field in the database. The field settings can no longer be changed.**

What can I do?

Thank you in advance!

# Answer
> 1 votes
You should use taxonomy to create a vocabulary named *Category* and add terms to it. Then add a taxonomy term reference field to your content type.

---
Tags: entities
---


title: Create And in contextual Filter

text:
# Question
Title: Create And in contextual Filter
I need to create AND in Contextual Filter, for instance: I Want to Get All English Node AND Italian Node, with particular Taxonomy. But I Can Have En and It, but even only en or only it, or even it, en ,de etc

Can I do it with Contextual Filters?

# Answer
> 0 votes
I'm not sure why you need an AND condition in the first place for this?

Should be enough to have a contextual filter for the taxonomy terms and a normal filter for the node language?

Note that translations are stored in a single node. I'm not sure what your expectations are about what exactly should be displayed. There are settings about which language should be used for display. You might have a problem with duplicates, though.

---
Tags: 8, views
---


# Question
Title: Can use taxonomies to I build a list of "conditions" that can be added to and referenced from different nodes?
I need to build a list of "conditions" that can be added to and references from different nodes. "Conditions" have a title and body. This screamed taxonomy but what's stopping me is that the "conditions" need the ability to modify the body field on a node-by-node basis.

It's a bit difficult to explain but I need:

1. A library of content that can be referenced and can grow, like taxonomy.
2. When referenced, the content has to be able to be modified but only that instance (don't modify the referenced entity site-wide). This will will be like an override for the reference.

I can to the first part with taxonomies but don't know how to override on a node-by-node basis as it's just a reference. It seems as if the referenced entity needs to populate a field on the node, and there it can be overwritten.

EDIT: Found the solution using this: https://www.drupal.org/project/entityreference\_autofill. I added a long text field on my taxonomy and my content and mapped them together.

# Answer
I'm not sure if you can get this done with taxonomies. However I would recommend you to have a look at either of those modules also (or "instead"?):

These 2 modules are also recommended in the (illuminating) article "Relativity Model for Drupal", for which this is an introduction to it (quoted from this linked page):

> The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:
>
> * Data architecture and data modeling merging as a single step through a documentation procedure.
> * Customized user interfaces that cater to individual workflows throughout permission roles.
> * Multi-level relational data structures that relate to other multi-level relational structures.
> * Mimicking the concept of database joins within Drupal's UI's. Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The small handful of modules (cfr. the last bullet) is detailed on Interface elegance and experience.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How do I use and show a vocabulary with multiple fields?
When I create a new vocabulary, I can create it in such a way that there are multiple fields. However, when I then create a content type with a field a term reference to that vocabulary, I only can see the name field from the vocabulary and not the other fields.

This regardless of the method I use, whether be radio buttons, check list, select list, autocomplete, autocomplete deluxe. I want to show those other fields so I can discriminate between two very similar, but with distinct values in the vocabulary.

For example, if it is a vocabulary of names, to add a date of birth which gets at least shown (and preferably is editable when adding a new term using autocomplete deluxe) when I fill in the form when adding an item of that content type.

# Answer
What you're looking for is Entity Reference. This will let you create a taxonomy term field on your content type and give you the option to render the entire term using the display of your choice (teaser, full etc).

Setting it up would be very similar to what you've already tried with term reference:

1. Create an entity reference field in your content type
2. Target type = taxonomy term
3. Set target bundle if preferred, then save
4. Under manage display, set the field format to rendered entity
5. Set the view mode to your preferred option (you would configure these options under your vocabulary manage display screen)
> 1 votes

# Answer
Install the Views and Entity Reference modules, create a new View and `Add` an Entity Reference Display:

Then add in the fields the Term Name and the Term ID (this is just an example, you can add more fields), click in the Term ID and check Exclude from display,

Save and click in the Term Name and go to rewrite the output of the title as `[name] - ([tid])`

Go to edit the settings of the format and check the Term Name, this will allow you to search by the Name of the Term.

Save the view.

Go to edit your Entity Reference field and select in the Mode Views: .... (like the following image) and select your View (in this case the name is: etiquetas - Entity Reference) and save the settings:

Then go to see the result when you go to add a new node:
> 1 votes

---
Tags: taxonomy-terms
---


title: No 'Div Container' button in CKEditor

text:
# Question
Title: No 'Div Container' button in CKEditor
I've got CKEditor 4.5.0 working on a Drupal 7.42 install. I'm now trying to find a way to wrap more than one HTML element inside a DIV (I want an image and caption to be wrapped in a single DIV).

On the *CKEditor Profile* I got 'Div container' selected under *Buttons and Plugins*. As I understand it this should give me a 'Div container' button in the Wysiwyg, which then opens a dialogue. But it ain't there.

All the buttons I've selected are in the toolbar. It's just that selecting 'Div container' doesn't appear to be doing anything.

I've tried manually installing the Div Container Manager but this also doesn't seem to have any effect. (And it shouldn't, because the plugin comes with the 'standard' CKEditor package).

Please tell me I'm missing something very obvious.

# Answer
Weirdly, I solved this by replacing the standard library with the full library. Seems odd as Div container is part of the standard library but it works.

When replacing the library, make sure to clear both Drupal's and your browser's cache.
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How to keep URL parameters on subsequent pages after a form is submitted?
I'm sending a referral form out to my email database and I've got it set up so that their email addresses get passed through and appended to the form URL like this:

http://www.holbrooktravel.com/referral-form?emailid=sarah@holbrooktravel.com

I've got a hidden field in the form that collects the 'emailid' value and stores it with the responses so they can be matched up with our database.

That's working well, but once someone submits their form they're sent to a thank you page (http://www.holbrooktravel.com/referral-form/thank-you) where they can click a button to go back to the form and refer someone else.

I can't figure out how to keep their 'emailid' value on the 2nd referral so those submissions can be matched up as well. If I'm on the right line of thinking then I need to somehow keep the URL parameters on both the thank you page and the link sending them back to the referral form.

Any suggestions would be very much appreciated!

# Answer
If you're able, and willing, to review/rework the current implementation you have for your webform submissions and the related "Thank you" page, you should consider getting the Rules module involved, e.g. to have the Rules module react to Rules event "After submitting a webform".

By doing so, you could then also use the Rules URL Argument module, which you can use to make the value of the URL argument available as new variable to Rules. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.
> 0 votes

---
Tags: forms, webforms, uri
---


# Question
Title: How do I unpublish a user's content with rules?
How can I unpublish a certain user's content when a certain rule triggers?

# Answer
> 1 votes
Here is a summary of what you'll need to get it to work using the Rules module:

1. Keep track of all node IDs of a user that need to be unpublished later on (= "*when a certain rule triggers*"). For this add an entity reference to the user's profile (multiple values allowed). And each time a node gets saved, you need to add the reference to that node as an extra value in this entity reference field (= **Rule 1**). So basically this is the "queue" of nodes for a user that need "post processing" after your "*certain rule triggers*". It is will serve as your entry point starting from the user's id to "access (find) the exact node ids again later on".
2. Create a Rules component (= **Rule 2**, though of type "component") with parameter just a "node id". All this Rules component has to do, is to "unpublish" the node indicated in the parameter. But you can add any Rules "Conditions" also if you'd need any (already now or later on if requirements change). E.g: only for specific content types or user roles, etc.
3. Create a rule (= **Rule 3**) containing a *Loop* that should be triggered ""*when a certain rule triggers*". The goal of this rule is to loop over each of the nodes in the reference field from Step 1, and in each iteration of that loop you use an action which is to invoke the Rule Component as detailed in Step 2 (and which uses the node id as a parameter). By using a Rules Component, you'll be able to add any "Conditions" you might need inside the "Loop".

# Video tutorials

If you're not familiar (enough/yet) with using *Loops* in the Rules module, then watch the video about List and loops.

For a video that is fairly similar to what's needed in step 2 and step 3, refer to the 2nd video (= Solution video) about Creating multiple back links. Some more details about how your scenario slightly differs from what is shown in that solution video:

* You are creating an entity reference **to** nodes also, but **from** a user (not a node).
* You only need the first parameter (= *Node to link to*) in your Rules component (you don't need the 2nd parameter).

# Answer
> 1 votes
The configuration would look like this:

1. Build a view that, when given a user ID as input, lists all the nodes that that user has posted.
2. Use view style bulk operations, and select the action unpublished node.
3. Set up a rule that triggers on user updates. (Is there one? I'm not sure...) As condition, compare the roles before and after user save to see if anything should be unpublished. As an action, let it call the view from.

Use this idea you can do that

# Answer
> 0 votes
Yes you can Unpublish the user content by Rules Module,

you can do by lot of possibilities, like: if user is deleted then Un publish the content of user, If user is In active then Unpublish the Content of the user.

Hope this one will help!!

---
Tags: users, rules
---


# Question
Title: Same Image in Multiple product with feeds
I like to upload a lot of commerce product from a csv file and I have one image for multiple product. I am importing images from a subdirectory of files, the field is in the csv: `public://productimages/PRODNUM.jpg`. It is working very nice, but when I use the same photo for multiple images it is makes a new image for every product. (PRODNUM.jpg PRODNUM\_1.jpg PRODNUM\_2.jpg PRODNUM\_X.jpg)

I like to use the same image for same products if the name is same.

I tried `filefield path` `filefield source` but not helped. If it possible I do not want to use the media module.

# Answer
If the images in the same place where the field is waiting for it the images will not multiple.
> 0 votes

---
Tags: commerce, feeds
---


title: multiple sort comments in drupal

text:
# Question
Title: multiple sort comments in drupal
like what you can see in this site, I want to have 3 tabs for comments.

oldest first

newest first

sort by likes

I've tested creating views and show in tabs but this way in too heavy!

is there a better way?

# Answer
Quick Tabs

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content.

Make 3 view blocks of each, and then create a quick tab of views and enable ajax so the other tabs load only when they get clicked.
> 0 votes

---
Tags: views, comments
---


# Question
Title: Is it safe for me to use _taxonomy_title_get_title() implemented by a third-party module?
I have installed the Taxonomy Title module 7.x-1.5 in order to change the grey content title on top of certain taxonomy pages. The module added a new field (*Term page heading*) where I add my custom titles. The title is changed as expected. Now I also need to use that same custom title in certain nodes, so I need to find out how to get the value added in that field.

After a look at the module code, I tried using `_taxonomy_title_get_title($tid)`, which works. Is it safe for me to use this function?

# Answer
Drupal adds a underscore to its function to mean they are for internal use only, and modules/themes should not depend upon them. For example, in Drupal 8, the `theme()` function was renamed `_theme()` as reported in theme() renamed to \_theme() and should not be called directly, which also states:

> It has been renamed to \_theme() and **is for internal use only**.

Then, it was removed.

Third-party modules follows the same naming convention: If the function name starts with an underscore, they don't want they use that function. This doesn't mean the function is necessarily going to be removed, but the maintainers could remove it at any time, even passing from version 7.x-1.5 to version 7.x-1.6.

So, if by *safe* you mean *sure that the code I am writing will not need any change*, then I would say no.
You could eventually write your own code that uses just *safe* functions made available from that module, using `_taxonomy_title_get_title()` as starting point; otherwise, you need to check your code is still working when updating that module. Depending on your specific use, you could also use tokens; the module defines \[term:title\] which is set using the function you are calling.

```
/**
 * Implements hook_tokens().
 */
function taxonomy_title_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'term' && !empty($data['term'])) {
    $term = $data['term'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'title':
          $title = _taxonomy_title_get_title($term->tid);
          if ($title) {
            $replacements[$original] = ($sanitize) ? check_plain($title) : $title;
          }
          else {
            $replacements[$original] = $term->name;
          }
          break;
      }
    }
  }

  return $replacements;
}

```

See also Call to undefined function \_taxonomy\_title\_get\_title(); it is for the version 6.x of the module, but users are essentially saying that, passing from version 6x-1.3 to 6.x-1.4/6.x-1.5, they get an error about the function `_taxonomy_title_get_title()` being not defined. (In fact, it was renamed `_taxonomy_title_get()`.) Since the development snapshot doesn't call `_taxonomy_title_get_title()`, I get they are talking of other code.
> 1 votes

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


# Question
Title: How to let users choose to hide fields in their profile?
Is there a way to allow users to choose to hide certain fields in their profile?

For example if building a job site, a user might choose to hide their name from others. Is there a way to do this?

# Answer
1. Create a checkbox field just below the field you want to hide on user profile page.
2. Now override the settings in template file.

Please follow the link allow users to choose whether certain profile fields are visible or hidden for detailed steps.

Also you can try out Profile2 Privacy module.

> This module extends Profile 2 by allowing administrators to create privacy levels as predefined groups or sets of profile fields on a per role basis. Users can then select from among the privacy levels to apply access control to their profile.
> 3 votes

---
Tags: users
---


title: Create Database Table in Run Time

text:
# Question
Title: Create Database Table in Run Time
I have an SQL CREATE TABLE.

```
CREATE TABLE myid_template_1
(
template_id int NOT NULL,
template_description character varying NOT NULL,

);

```

I want to know its equivalent query structure in Drupal 7 to create tables at run time. I tried the code below, which it didn't return any error. I wonder if it successfully creates a table, since I could not find the location of the table I created.

```
function myid_create_db_fields(){
    $template_id = 1;
    $schema['myid_template_'. $template_id] = array(
        'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
        'fields' => array(
           'template_id' => array(
               'type' => 'int',
               'not null' => TRUE,
           ),
           'template_description' => array(
               'type' => 'character varying'
               'not null' => TRUE,
           )
        ),
    );
    db_create_table('myid_template_' . $template_id, $schema);
}

```

PS: I don't want to use `hook_schema()` because the table is not created when the module is installed.

# Answer
You're passing the wrong thing as the schema definition.

This is what you need:

```
$schema['myid_template_'. $template_id] = array(...);

db_create_table('myid_template_' . $template_id, $schema['myid_template_'. $template_id);

```
> 1 votes

# Answer
You should implement hook\_schema

Code sample from the hook's explanation

```
function hook_schema() {
  $schema['node'] = array(
    // Example (partial) specification for table "node".
    'description' => 'The base table for nodes.',
    'fields' => array(
      'nid' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'vid' => array(
        'description' => 'The current {node_revision}.vid version identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'type' => array(
        'description' => 'The {node_type} of this node.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'title' => array(
        'description' => 'The title of this node, always treated as non-markup plain text.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'indexes' => array(
      'node_changed' => array('changed'),
      'node_created' => array('created'),
    ),
    'unique keys' => array(
      'nid_vid' => array('nid', 'vid'),
      'vid' => array('vid'),
    ),
    // For documentation purposes only; foreign keys are not created in the
    // database.
    'foreign keys' => array(
      'node_revision' => array(
        'table' => 'node_revision',
        'columns' => array('vid' => 'vid'),
      ),
      'node_author' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
    'primary key' => array('nid'),
  );
  return $schema;
}

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: How to get vote results from node reference through views?
I have two content types: 1. Restaurant page 2. Write a review page The write a review page has node reference url widget field and also the fivestar rating field. The image attached below will explain more:

I have created a view page, where I want to get vote average results for each restaurant (also if possible than on each individual restaurants page too). I basically want average result of ratings given to each restaurant page by the node reference content type which is write a review page. Below are two images explaining my view:

And the preview:

Now I am really not sure what I am doing wrong here, I changed aggregation settings for all randomly to average to count to all the possible scenarios but nothing seems to work. The votingapi\_vote table is also empty, I know that fivestar doesnt necessarily use those tables to store, but then how could I display the stars or even the average of all the ratings that restaurant has got?

------------ update 1 -------------------------

Here is the relationship content type which I am getting:

# Answer
> 1 votes
Can you add a relationship of referenced node? or referenced write a review?

If not use the entity reference module instead. Add an entity reference field, with auto complete widget. Bundle type: Node.

Then in view add a relationship of referenced write a review.

---
Tags: nodes, views, rating
---


title: Date range2 Field Validator not firing

text:
# Question
Title: Date range2 Field Validator not firing
I am attempting to create a validator on a birthday (date) field I added to the user. The validator is setup as such but it never fires when I test it by registering a new user on the front-end.

Anyone have any ideas why this validator isn't firing?

# Answer
A possible solution that might help to simplify the challenge in your question, is the fairly new Math Field module (for D7). Some more details about this module (from its project page):

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

By creating some auxiliary field(s) (calculated via the Math field), you may be able to complete your puzzle via some additional logic implemented via the Rules module, to actually verify "18 Years or Older" (which I believe is the actual validation you want to implement).

For more details (step-by-step instructions), refer to either of these links:
> 0 votes

---
Tags: forms, datetime
---


# Question
Title: Drupal Commerce: Print order for warehouse
I followed Drupal Commerce: Print order? solution:

> Through Rules you can achieve this by creating a Rule within the Rules module:
>
> First step create a custom rule at /admin/config/workflow/rules/reaction/add Select the React on event: "Completing the checkout process" Add a new Action: "Send mail" Once you add the email addresses from/to, than add the replacement fields in the body text of the email. I suggest: \[commerce-order:order-number\], \[commerce-order:type\], \[commerce-order:commerce-line-items\]. But you can figure that part out. Save your Rule.

I receive the email but I do not have a proper list of ordered products, instead I have numbers. One per article but the change on each order even if the articles are the same.

How can I have a proper order listing in the email?

# Answer
> 2 votes
You will want to use the Commerce Message module: https://www.drupal.org/project/commerce\_message

This module provides a `!order-summary` token which embeds an order's line item summary. This token only works, however, if the Message bundle has the `message_commerce_order` field.

You can either programmatically add this to a new Message bundle. Or, the easy route, clone the default admin notification and adjust as needed!

---
Tags: commerce
---


# Question
Title: It does not work when installed as "subsite"
I tried to install Drupal 8.03 on a windows 7 64 bit server, with MySQL, Apache and PHP 7.03, using the default install procedure / script.

Drupal is only one of the applications on the website and that is probably different from what Drupal 8 seems to expect.

The website is like https:/www.mysite.nl and overall root folder is x:\myroot\homepage. Drupal, however, is installed in x:\myroot\homepage\drupal and it is supposed to be accessible via https:/www.mysite.nl/drupal.

Back to the installation. To a "certain" extend that seems(!) to work. That will say the install script runs and ends. But than I want to access Drupal and that does not work. I can not access any thing "page missing". Both the base folder and the base url is not what Drupal expects (e.g. Drupal generates https:\www.mysite.nl\xyz where that should be https:\www.mysite.nl\drupal\xyz and I can not change that (at least not from the UI which is not accessible, assuming there is a setting for that).

So drupal seems is completely lost, does not understand what its base url is and does not understand where the files are (both at least the url should be a question during installation!!!!!).

By the way I never really used other drupal versions, but from a last year test install my impression is that this problem did not exist in drupal 7.

I do not know how to solve this. Hope you can help and perhaps initiate a few corrections/extensions in Drupal 8.

# Answer
> 2 votes
Look for this code in the `.htaccess` file in the root of the Drupal site's filesystem:

```
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal

```

and remove the '#' from the beginning of the `RewriteBase` line. That should tell Apache/Drupal how to properly rewrite URLs for your case.

---
Tags: 8, uri, installation
---


title: Change the updated timestamp for users

text:
# Question
Title: Change the updated timestamp for users
I have a custom module that do some processes after a user entity is updated. I need to just trigger a timestamp update so my module can act on them accordingly. I wrote a script that is going through all my ~350000 users and doing this :

```
$loaded_user = user_load($uid);
user_save($loaded_user);

```

While this is working, the process is taking too long to finish. Is there a faster way to do this?

# Answer
Here is an idea about running this in a more efficient way:

```
<?php
  $loaded_user = user_load($uid);
  $user->changed' = time();

  field_attach_update('user', $user);
?>

```

I am not 100% sure if this is gonna work for your setup the way you want to, i.e. if the hook you implement in your module is going to be called (not enough information there).

Let me know and I can give you an updated answer.

Cheers
> 0 votes

---
Tags: users
---


# Question
Title: How do I programmatically set the minimum order subtotal limit?
I am using the Ubercart module for my site. I need to programmatically set the minimum order subtotal. I need to create a custom module to apply this condition, but I am not getting any hook.

Do you have any suggestion?

# Answer
> 0 votes
If you would like to validate minimum subtotal directly in the cart, you could use hook\_form\_alter.

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'uc_cart_view_form':
      //add own validate function
      $form['#validate'] = array('mymodule_subtotal_validate');
    break;
  }
}

```

Then define the content of the validation function:

```
function mymodule_subtotal_validate($form, &$form_state){
  //validate only if we are going to submit the cart form
  //there are others possibilites, when the validate handler is called,
  //such as quantity change, etc..)
  if(isset($_POST['op']) && $_POST['op'] == t('Checkout')){
    //access cart items and their quantity
    $sum = 0;
    foreach($form_state['values']['items'] as $key => $item){
      $product = node_load($item['nid']);
      $qty = $item['qty'];
      $sum += $product->price * $qty;
    }

    if($sum < YOUR_SUM){
      form_set_error(null, 'Your items subtotal is less than minimal subtotal.');
    }
  }
}

```

---
Tags: 7, ubercart
---


title: jcrop not working

text:
# Question
Title: jcrop not working
I can't get jcrop to work

It gives

Uncaught TypeError: $(...).Jcrop is not a function

on $('#image1').Jcrop({

alert($('#image1').value) gives undefined

```
    $form['file1'] = array(
            '#type' => 'file',
    '#name' => 'browse_file1',
        '#id' => 'browse_file1',
    '#attributes' => array('onchange' => 'JavaScript: fileSelectHandler1();'),
    '#prefix' => '<div class="image-row1">
                    <p class="row-title">Add images to your listing</p>
                    <div class="form-row image-row">
                        <span>image path name</span>',
    '#suffix' => '</div>',
  );

$form['file6'] = array(
            '#type' => 'file',
    '#name' => 'browse_file6',
        '#id' => 'browse_file6',
    '#attributes' => array('onchange' => 'JavaScript: fileSelectHandler(browse_file6, image6);'),
    '#prefix' => '<div class="image-row6">
                    <p class="row-title">Add images to your listing</p>
                    <div class="form-row image-row">
                        <span>image path name</span>',
    '#suffix' => '</div>
                    <div class="existing-images">
                        <div id="the_image1" class="existing-image">
                            <a href="" class="delete">X</a>
                            <img name="image1" id="image1" src="" alt="">
                        </div>
                        <div id="the_image2" class="existing-image">
                            <a href="" class="delete">X</a>
                            <imgname="image2" id="image2"  src="" alt="">
                        </div>
                        <div id="the_image3" class="existing-image">
                            <a href="" class="delete">X</a>
                            <img name="image3" id="image3" src="" alt="">
                        </div>
                        <div id="the_image4" class="existing-image">
                            <a href="" class="delete">X</a>
                            <img name="image4" id="image4"  src="" alt="">
                        </div>
                        <div id="the_image5" class="existing-image">
                            <a href="" class="delete">X</a>
                            <img name="image5" id="image5"  src="" alt="">
                        </div>
                        <div id="the_image6" class="existing-image">
                            <a href="" class="delete">X</a>
                            <img name="image6" id="image6"  src="" alt="">
                        </div>
                    </div>',
    );

```

Am I not defining the images properly as the jquery files are all in the right order? Thanks

# Answer
If Jcrop is not a function, I would say either...

1. You have not added the jcrop library to the header correctly. Are you using a jcrop module, or adding it yourself?
2. You have the incorrect version of JQuery, try JQuery Update
3. Try changing all your instances of the "$" shortcut to "jQuery"
4. Enclose all your jQuery code in a function with jQuery as a parameter and the $ shortcut
> 1 votes

# Answer
There turned out to be two versions of one of the jquery files
> 0 votes

---
Tags: javascript
---


title: How to combine two menu's in Drupal

text:
# Question
Title: How to combine two menu's in Drupal
I'm building a site with 2 menu's. One is the main menu, the other one is similar to the user menu.

The user menu is only displayed in a panel on the frontpage, the main menu is always visible. To keep the user-menu options available I'd like to add them to the main menu as well so they are always accessible too.

I thought of appending the user-menu to the main-menu in my custom template.php like below, but that gave me just the main-menu.

```
function THEME_preprocess_page(&$variables) {
  $variables['main_menu'] = array_merge(menu_main_menu(), menu_navigation_links('menu-myoptions'));
}

```

I was using the main-menu-block, so I thought that could be the reason the altered menu is not showing up. (The block might load the menu directly). But when I user `render($main_menu)` in my page.tpl.php it doesn't work eighter.

Am I missing something?

# Answer
> 0 votes
I ended up using Menu Minipanels.

> A system for building "megamenu" -style dropdown menus using Mini Panels, which provides tremendous flexibility in what can be displayed.
>
> Click-by-click beginner's tutorial: http://drupal.org/node/984560#comment-3922442

It allowed to me to create a panels lay-out and place the menu-blocks I wanted in there. To front-end users it looks like it is one menu.

# Answer
> 1 votes
Instead you can try this Advanced Menu module, Menus can now be merged into other menus. This allows users with the appropriate permission to add links to other menus which are then displayed as if there were a single menu.

> Example:
>
> Create new role "News Manager"
>
> Create new user "News Editor"
>
> Create new menu "News Releases", Set "News Manager" as an editor for the menu.

---
Tags: routes, theming
---