title: SMS Reminders for Course Signup module

text:
# Question
Title: SMS Reminders for Course Signup module
I am using Drupal 7 version of Signup module. It send email reminders before the course starts X number of days. Is it possible to send SMS reminders using another module. If not then where i should be looking in the code ?

thanks

# Answer
> 0 votes
You can use any sms integration api. I personally like Twilio.

There is a module for twilio integration as well: link

You will need to find a place from where the email has been sent, it would be in the code or possibly through Rule module, in either case you need to add a line of code which should utilize twilio api and send sms to the destined users.

---
Tags: 7
---


# Question
Title: Form Display: How to move elements out of the advanced container?
I want to tweak the *node add/edit form* for one of my content-types and rearrange the fields in different groups.

I use the Field Group Module to setup the different groups.

On the *Manage Form Display* settings of the content-type I rearrange the Fields, which works fine for all fields but "Authored by", "Promoted to front page" and so on. All this fields are rendered in an "advanced" container, no matter what.

This is also part of the classy theme file node-edit-form.html.twig

```
  <div class="layout-region layout-region-node-main">
    {{ form|without('advanced', 'actions') }}
  </div>
  <div class="layout-region layout-region-node-secondary">
    {{ form.advanced }}
  </div>

```

Is there any way to break this up, so I can move the containing fields into different groups, just like any other field?

# Answer
These Fields are organized in different groups in NodeForm::form.

So the settings from *Manage Form Display* wont work until the `#group` property of the fields is unset or the surrounding container is unset.

This can be done with one of the *form alter hooks* in your theme or custom module.

For example the hook\_form\_BASE\_FORM\_ID\_alter:

```
function your_theme_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    unset($form['author']);
}

```

This will unset the author container. The containing fields *Authored on* and *Authored by* can than be moved around with the *Manage Form Display* Form.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: What does the computed code do for a computed field in content type
I have content type field called '`field_p_bo`' and it have the computed code as follows

it causes some problem since it affect the saving of this content type , This code is there for some other fields too . What will happen when i remove the computed code ? will it affect any other part of the content type ?

# Answer
The code fetches the id of the node\_project.

For example if the node's project field is set 'Foo' it will get the id of that row where it was saved. As its not clear from where $node comes whether its current loaded node or any other node. But it seems that in ***computed field you are storing the ID of the project***

What I think is causing the problem is if project names are FOO and FOO\_BAR the query will result both the ids which can cause to store incorrect ids.

You can simply remove the like operator and add equality.
> 0 votes

---
Tags: 6, entities
---


# Question
Title: Drupal commerce re-indexing causes exception
I'm trying to re-index all my products on my Drupal commerce website. When I do so, I get the following error message:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /en/batch?id=130&op=do StatusText: Service unavailable (with message) ResponseText:

When I go to `watchdog` it shows me this error:

> EntityMetadataWrapperException: Unable to get the data property status as the parent data structure is not set. in EntityStructureWrapper-\>getPropertyValue() (line 438 in /sites/all/modules/entity/includes/entity.wrapper.inc).

I tried finding out if there were any specific products or entities with their status not being set. When I run the following query in my database, it shows me that there are no products without status. (They all show up with 1 as their values.)

```
SELECT * FROM  `commerce_product` LIMIT 0 , 500

```

When I put the batch on doing 1 product at a time, it does 18 of the 193 products and then stops and returns the error message.

What I'd like to know is:

1. How do I check which product is the culprit?
2. How do I find my indexed items, and how can I find out where it goes wrong? (I'm not using Apache Solr.)

I'm also not quite sure about what is meant by 'the parent data structure is not set'. If anyone could provide any insights, I'd very much appreciate it.

# Answer
> 1 votes
It sounds like a field got messed up somewhere. Try running Commerce Repair and seeing if that fixes the problem.

---
Tags: commerce, entities, search
---


# Question
Title: Adding Pager to entity referenCED field display
I have two content types: Parent and Child

I have an entity reference field (called "Link") in parent content type referencing it to child content type.

I am using inline entity forms module for the entity reference field .

I want to know if there is a way to achieve the following:

Question 1:

I want to have a read more button on parent content type, which would open the first entity referenced child page.

Question 2:

I want to have a pager in the child page which would link to the other child pages of the same entity referenced parent content type. (something similar to what books module provides for book child in child pages)

Any help would be highly appreciated. Thank You.

# Answer
> 0 votes
There might be better way of doing that.

But one of the way will be to use views module

**Answer to question 1:**

1. Go to your\_site/admin/structure/types/manage/content\_type/display
2. Change the reference field format to Rendered entity
3. Click the setting and make sure Show links is checked

**Answer to question 2:**

1. Install the module views if you don't have it already
2. Go to yoru\_site/admin/structure/views/add
3. Give your view name for example read more button to parent content type
4. Unchecked Create a page and Check Create a block
5. Click Continue & edit
6. Change format to "Table"
7. Click add filed and select the fields you want to show
8. Click add Filter criteria and select the criteria you want
9. Click the Advance and Add Contextual Filters
10. SelectContent Content: Nid"
11. Select Relationship as content entity referenced from your\_xyz
12. Change the option for When the filter value is NOT available to Provide default value and select Content ID from URL.
13. Change When the filter value IS available or a default is provide to Specify validation criteria and select Content from Validator select field, and select the parent content.
14. Make sure Filter value format is = to Node ID
15. Make sure Action to take if filter value does not validate is = Hide view
16. Click Apply
17. Add a Relationship, Click add and select Entity Reference
18. Click Save.
19. Go to yoru\_site/admin/structure/block, search for the new view name black you just added.
20. Click configure change the Visibility settings to content type and select the parent content type.
21. Set the Region where you want the black to be display.

# Answer
> 0 votes
I solved my first question with the help of the detailed instructions from Yama as below:

1. Create a block view of html list .
2. Use relationship: Entity Referencing.
3. Click Advance and Add Contextual Filter
4. SelectContent Content: Nid"
5. Select Relationship as content entity referenced from your\_xyz
6. Change the option for When the filter value is NOT available to Provide default value and select Content ID from URL.
7. Change When the filter value IS available or a default is provide to Specify validation criteria and select Content from Validator select field, and select the parent content.
8. Make sure Filter value format is = to Node ID
9. Make sure Action to take if filter value does not validate is = Hide view
10. Click Apply
11. Click Save.
12. Go to your\_site/admin/structure/block, search for the new view name block you just added.
13. Click configure change the Visibility settings to content type and select the parent content type.
14. Set the Region where you want the black to be display.

Instead of Steps 12 to 14, I used Display Suite, Block Field feature.

It works like a charm.

---
Tags: entities
---


# Question
Title: programmatically add line item of commerce_discount type to order
I want to programmatically add line item of commerce\_doscount type to my order, I test below code,it is correctly add a record to line items array but not show in order list even I refresh the order I dont see anything in order table .

```
$amount = trim($amount);
  $basePrice = commerce_price_field_data_auto_creation();
  $basePrice['amount'] = $amount;
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
if ($amount) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
     $line_item = entity_create('commerce_line_item', array(
    'type' => 'commerce_discount',
    'line_item_label' => 'my test',
    'quantity' => 1,
));
    // Wrap the line item and product to easily set field information.
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
// Set the unit price on the line item object.
$basePrice = commerce_price_field_data_auto_creation();
$basePrice['amount'] = $amount;
  $line_item_wrapper->commerce_unit_price = $basePrice;
// Save the line item now so we get its ID.
  commerce_line_item_save($line_item);

      //  $line_item = commerce_line_item_save($line_item);
        // Add it to the order's line item reference value.
$order_wrapper->commerce_line_items[] = $line_item;
     //commerce_order_save($wrapper);
      commerce_order_save($order);
$order = commerce_order_load($order->order_id);

        // Recalculate discounts.
      //  ym($order);
        commerce_cart_order_refresh($order);

```

also I look at `discount` module and try below code

```
 module_load_include('inc', 'commerce_discount', 'commerce_discount.rules');
   $amount = trim($amount);
  $basePrice = commerce_price_field_data_auto_creation();
  $basePrice['amount'] = $amount;
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  commerce_discount_add_line_item($order_wrapper,'commerce_discount',$basePrice);

```

but return me **EntityMetadataWrapperException: Unable to get the data property commerce\_total as the parent data structure is not set. in EntityStructureWrapper-\>getPropertyValue()**

# Answer
> 2 votes
Don't reinvent the wheel, here. Discounts provides functions for apply discounts to orders:

```
// Pass in an $order or $product that has been entity_metadata_wrapper()ed.
// And pass in a discount name.
commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, $discount_name);

// Same thing, but a percentage.
commerce_discount_percentage(EntityDrupalWrapper $wrapper, $discount_name);

```

If you must reinvent the wheel, use these functions as examples to guide what you are doing.

---
Tags: commerce
---


title: Equivalent of node_type_get_types()

text:
# Question
Title: Equivalent of node_type_get_types()
Can somebody help mi with use of node\_type\_get\_types() in Drupal 8?

### Code in Drupal 7

```
function node_type_get_types() {
  return _node_types_build()->types;
}

```

### Code in Drupal 8

```
function node_type_get_types() {
  return NodeType::loadMultiple();
}

```

This was my code in Drupal 7. How to now use node\_type\_get\_types in Drupal 8?

```
$options = array();
  foreach (node_type_get_types() as $type) {
    $options[$type->type] = $type->type;
  }

```

# Answer
Node types are (config) entities, so they have the same methods available as others. Specifically, relevant for you, all entities have id() and label() methods:

```
use Drupal\node\Entity\NodeType;

$options = array();
foreach (NodeType::loadMultiple() as $type) {
  $options[$type->id()] = $type->label();
}

```

Those methods are defined on `\Drupal\Core\Entity\EntityInterface`, you can use them anything that's an entity and that includes almost every type of content and configurable thing, nodes, users, roles, views, image styles, ...
> 4 votes

---
Tags: nodes, 8
---


# Question
Title: Installing extra/additional plugins for standalone CKEditor module library
I have the CKeditor plugin installed by itself (i.e. not using WYSIWYG module.) Then, it uses a CKEditor library located in sites/all/libraries/ckeditor. This works fine. I'd like to add more plugins to it; namely, the footnotes plugin. (For the moment, please refrain from "just download a new library from ckeditor.com and replace it"; there were other issues/considerations involved.)

Now, I see this everywhere when I try to look for a solution

```
config.extraPlugins = 'footnotes';

```

I tried adding that to admin/config/content/ckeditor/edit// -\> Advanced Options -\> Custom JavaScript configuration, but it white screens the editor.

I tried adding it to the config.js in sites/all/libraries/ckeditor like below, but it had no effect.

```
CKEDITOR.editorConfig = function( config ) {
  config.extraPlugins = 'footnotes';
};

```

I can't really add it to a ckeditor.config.js file, dump that file in my theme, and choose "Yes" for "Load ckeditor.config.js from the theme path", since (for content creation/editing) it uses the admin theme which is different from the theme we're developing.

So, I'm at a loss. The only other thing I can think of is to use a hook in the module we have for the site, but I'm not sure if that's write/what hook would be called.

Is it just me, or does it seem like clear documentation on how to manage CKEditor in Drupal is severely lacking? Any help would be appreciated.

UPDATE: After some testing, it looks like the "Custom JavaScript configuration" is supposed to work, but it is possibly broken for CKEditor 4.4+ I read something (can't seem to find it now) that suggested the plugin/widget import was broken on 4.4+, so I changed to 4.3 and the extraPlugins worked. Now, I wasn't able to get footnotes working (which is what kicked this whole thing off), but some other plugins that previously failed during the same steps now work on 4.3. So, there's that. I'm wondering now if it's something with footnotes itself.

# Answer
> 5 votes
Here are the steps about how I am doing it:

1. install CKEditor using the CKEditor module and **NOT** through using the wysiwyg module.
2. Put plugin in `sites/all/modules/ckeditor/plugins` and **NOT** in `/sites/all/modules/ckeditor/ckeditor/plugins`
3. Go to `/admin/config/content/ckeditor` and click edit on the profile you're using.
4. Under Editor Apperance, from Available buttons, drag up your plugin icon to the Current tool bar.
5. Scroll down a bit and you will see a Plugins section.

6. Checkmark your plugin and save changes.

**PS**: **Here is my CkEditor Global Profile settings** `/admin/config/content/ckeditor/edit/`

---
Tags: 7, wysiwyg, theming
---


# Question
Title: Drupal embed view in email sent by views
I've configured a rule to send an email after a commerce order is placed containing products of a particular type. That works fine. The body though is a view token (\[views:embed:golf\_registration\_information:default\]) pulling in specific order info (couldn't do this through the rule with the info I wanted to include). However in the email, I'm getting "edit view" links in a few places, which obviously I don't want.

Here's what the link looks like: http://website.com/admin/structure/views/view/golf\_registration\_information/edit/default?destination=checkout/451/paypal\_ec

I can't figure out how they are getting in there. Is there a setting I'm missing in Views? It appears as the first thing in the body, and then within the body above the line items table. Obviously I didn't add anything within the Global Custom Text field that's outputting the fields.

Modules I'm using: D7, Commerce, Commerce Rules Extra, Rules, Mimemail, Views, Token Embed Views

# Answer
Sounds like you need to disable contextual links:
> 3 votes

---
Tags: views, commerce, rules, emails
---


title: Add custom HTML to custom field

text:
# Question
Title: Add custom HTML to custom field
In a module, I have defined a custom field. Using hook\_field\_formatter\_info() and hook\_field\_formatter\_view(), I can manage the display of every item (value) within that field. I want to allow the use of multiple values of this field.

***How can I add extra HTML to this 'collection'? Programmatically, from within my module.***

For example, let's say my module adds a 'fruit' field, that allows me to enter its name and its color. Now, I'd like to display this as such:

```
Name: Strawberry. Color: Red
Name: Orange. Color: Orange
Name: Lime. Color: Green
<some>Extra Html</some>

```

How to add that extra last line?

I can find references to hooks that should do it, but I simply don't understand how to tie all these pieces of information together. I suspect I have to work with:

hook\_field\_prepare\_view https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook\_field\_prepare\_view/7

I also found this resource suggesting these hooks: http://www.failover.co/blog/drupal-7-custom-field-formatter-hooks-overview

and that I should manipulate the render array.

And I tried just adding an extra element to the array, an extra delta:

```
$element[] = array(
    '#type' => 'markup',
    '#markup' => "Test HTML"
);

```

But is seems to get ignored by Drupal

# Answer
It turns out all I needed to do was to use hook\_field\_prepare\_view() to add an extra, empty elements to the $items array

```
/**
 * Implements hook_field_prepare_view().
 */
function threejs_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items)
{
    $items[1]['footer'] = array( );
}

```
> 1 votes

# Answer
Same as @Ideogram but here is my full code. For example I have 4 images. My formatter makes the first image the main image and the rest including the 1st image thumbnails. I need to add the extra $item to the beginning.

```
/**
 * Implements hook_field_formatter_prepare_view().
 */
function yourmodule_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  foreach ($displays as $key => $display) {
    if ($display['type'] == 'my_formatter') {
      // We need to add an extra item for the main image.
      if (isset($items[$key][0])) {
        array_unshift($items[$key], $items[$key][0]);
      }
    }
  }
}

```
> 1 votes

---
Tags: 7, hooks, entities, theming
---


# Question
Title: Custom Module: db_select title AND body?
I'm a little confused by how the node data is stored in the database. It seems like the title is stored in the db "node," while the body is stashed field\_data\_body, and custom fields are placed elsewhere.

I have create a custom module that pulls certain pieces of content, but I need to match up the title with the body. I've been successful pulling my list of titles:

```
    function foo() {
      $query = db_select('node', 'n')
       ->fields('n', array('type','title', 'nid'))
       ->condition('type', 'fooBar')
       ->condition('status',1)
       ->execute();
          return $query;
      }
      $result=foo();
        foreach ($result as $node) {
         $id = $node->nid;
        }

```

How can I match each of these with their bodies?

Thanks! -JB

# Answer
If you want directly include the body within your result set, you can do a join on the `field_data_body` table.

```
$query = db_select('node', 'n');

$query->leftJoin('field_data_body', 'd', '(d.entity_id = n.nid AND d.entity_type = :node)', array(':node' => 'node'));

$query
    ->fields('n', array('type', 'title', 'nid'))
    ->fields('d', array('body_value', 'body_summary', 'body_format'))
    ->condition('type', 'fooBar')
    ->condition('status', 1)
    ->execute();

```
> 1 votes

# Answer
You are correct - Drupal stores the data for fields inside of separate tables. Depending on your use case, you may find it easier to use node\_load() which will load the entire node object with all the field data.
> 1 votes

---
Tags: database
---


title: Nodes appear out of line - views

text:
# Question
Title: Nodes appear out of line - views
Does anyone know what causes nodes to appear out of line when pulled to a view? Examples:

Photo profiles here: https://international.permaculture.org.uk/about

Topics listed at the bottom of this page: https://international.permaculture.org.uk/nextbigstep

I am wondering if it is because not all fields are populated - or because there are no teaser breaks and an uneven amount of body text?

Is there a way to stop this happening?

# Answer
> 0 votes
I think that you will find the answer here:

Responsive column resets

> With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and our responsive utility classes.

If it is too difficult to add above mentioned classed divs in the layout (can be done via templating Views) you should add your own styling wherein you use the n-th group of CSS selectors to clear at the different media queries.

The problem arises from the fact that your views rows do not have equal height and therefore do not flow as you want it to.

Also look at this post Bootstrap 3.0:responsive column resets section of the documentation

And for a module to assist you can try this: gido's sandbox: Views Bootstrap Responsive Grid

> Views Bootstrap Responsive Grid module enable you to take advantage of the Bootstrap 3 Grid System columns reset. With this module you can define the number of items per row for each breakpoints. All of this within the great configuration settings of the View module.

---
Tags: views
---


# Question
Title: Current password required to change password for self-registered users. No password was ever set
I cannot figure out how to validate users through email using drupal.

at `admin/config/people/accounts` I have **Require e-mail verification when a visitor creates an account** checked, and under *Who can register account* I have it set to **Visitors**.

When I go to create a new account, it says a success message and no email is sent. No errors, nothing in the logs. If I request a password, it sends that email no problem. I can also change my password without entering a current password when using the request password link. So the site is sending emails, just not validation/registration emails.

I have to use rules in order to send the registration emails because the emails are not sending and we have a deadline. I got rules to successfully send the emails but the one time validation link does not exist in the email.

I had to then download Login One Time in order to show a validation link in the email.

After clicking the email and successfully logging in as that newly created user, I am unable to change my password because the form is asking for a current password, which is not available for the user to even populate at the registration step.

I have tried using logintoboggan and tried generating temp passwords to send to the user but the token provided by login-toboggan shows up as nothing when the email is sent.

I am seriously confused as to why this is such a difficult process to achieve. Is email validation this difficult out of the box with drupal?

Does anyone know why drupal is prompting me for the **current password** for newly created users?

**Is there something I am missing as to why only registration/validation emails won't fire from my website, but other system emails do?**

# Answer
I have solved my issue by re-installing the login one time module and clicking the **Ignore the current password field** checkbox.

This hides the Current password field for the one time login link, and everytime after requires the user to provide a Current password if they want to change their email, password ect.

The problem is that this website will still ask for a current password for validation links if I uninstall the Login-one-time module, which makes no sense to me.
> 0 votes

# Answer
I've seen this issue, and it sounds like it's the one described here on d.o.

For me, using Simple Password Reset ended up being the solution (and with it, its "brief" login form bypass method).
> 0 votes

---
Tags: 7, rules, authentication-authorization, users
---


title: Save button missing

text:
# Question
Title: Save button missing
I have created a custom type under Drupal 8 Admin page. but when create a new custom type content, "Save and Publish" button is missing. while, the button is shown on "Basic page" content.

I have to click on "Preview" button, then click on "back to content editing", Drupal 8 then redirect me to Edit page, and a button "Save and keep Publish" been shown.

# Answer
> 16 votes
Ok, post an answer here.

This is because I did turned on "Preview before submit" option.

to turn it off, 1\> Edit the content type 2\> Click "Submission form settings" 3\> Set "Preview before submitting" to Optional.

But I just find a problem/bug , when you turn on "Preview before submit". I am unable to update/modify my content, it always redirect me to "Preview" page.

here is how to reproduce it.

```
1> turn on "Preview before Submitting" option
2> create a content, at first, you can save the content.
3> then try to modify / edit that content again,you will find out
    you are unable to save the content.

```

---
Tags: nodes, 8
---


title: product variation switcher

text:
# Question
Title: product variation switcher
Hy Drupal Masters!

My question is about commerce module. I managed to do the followings:

* create taxonomies (for creating menu and categorizing products - type - , AND for classifying products in other context - package)
* create product types
* create the appropiate content types to product types
* creating product variations(variations based on 2 fields in content types: "type" and "package" )

For example I have 3 menu-category with products: prod1(products of category: prod1-1, prod1-2, prod1-3), prod2(prod2-1, prod2-2, prod2-3), prod3(prod3-1, prod3-2, prod3-3)

Each product in one category has 3 variation: small, medium, large At the moment, if I click one of the categories, the product list appear with the good products, and each product has only one variation. (eg. I click prod1, I'll see the products, like: prod1-1small, prod1-2small, prod1-3small)

How I expected...but:

I wold like to place a selector(select list or checkboxes, I don't mind) to the top of the product list under each category that is containing small, medium, large elements. Than if I select "medium", the product list needed to change according to the selection.(I would like to see the: prod1-1medium, prod1-2medium, prod1-3medium)

In a product details page I could do this, but in a product list page, I couldn't.

I am using drupal 7

Please somebody help me!

# Answer
I have a solution for this.

First: I have just created one product type, with the field 'somethingTermReference'(term reference), wich will be the base of the production switcher.

Second: I created content types for every product category, for displaying them. Each content type has a type field with distinct values.

Third: I created views for every product category and there are 3 filter criterias for each view: published content, content type(actual product category), and one exposed filter on a product reference 'somethingTermReference' field.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to set configuration value for drush site install?
I have set a central translations directory(sites/all/translations) for my multisite installation profile so that each site does not have to download translations that were already downloaded.

I have set this via global settings file that I am including in the site's settings file, but it did not helped. Then I have added locale.settings.yml config into the profile, still no change. This works always AFTER the site was installed.

In the site installer there is a condition that checks if the config value for the directory exists in the global config variable, it will use that value or if not it will use the site's own translations directory by default.

So I think that during the installation process using config won't work and the only way is to use the global config variable.

So my question is how I can provide this variable to drush's site install command?

I am talking specifically about this: core/includes/install.core.inc:411

```
  // Register the file translation service.
  if (isset($GLOBALS['config']['locale.settings']['translation']['path'])) {
    $directory = $GLOBALS['config']['locale.settings']['translation']['path'];
  }
  else {
    $directory = $site_path . '/files/translations';
  }
  $container->set('string_translator.file_translation', new FileTranslation($directory));
  $container->get('string_translation')
    ->addTranslator($container->get('string_translator.file_translation'));

```

# Answer
> 0 votes
It is not possible to override this since the install\_check\_translations() has this hard-coded.

---
Tags: 8, drush, multi-sites, installation, i18n-l10n
---


title: Sorting Views by Day and Month only

text:
# Question
Title: Sorting Views by Day and Month only
For a Birthday field using the Date module, Views sorts it by year. This puts the dates in basically random order once you format it to display only the month and the day. Could it sort by day and month only?

**Extra bonus question**: Could Views sort the Birthdays in context of the current day so the upcoming Birthdays float to the top?

# Answer
Never used this module, might be worth looking into. It has Views integration.

## Birthdays

> The Birthdays module allows users to add their birthday to their profile. It also lists birthdays on a seperate page and in different blocks. Users can receive an e-mail on their birthday automatically, and the administrator can receive periodic reminders of who are having their birthday. Uses Profile module from core.
> 0 votes

---
Tags: 7, views, datetime
---


title: Admin form not validating in a module

text:
# Question
Title: Admin form not validating in a module
I am coding a Drupal Module wich limits the node creation to users who bought some products. e.g. A user bought a 5 photos + 5 videos pack, the module limits his number of photos & videos he can create to 5.

I got an issue with the admin form :

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

    foreach ($products = product_node_limit_get_products() as $result) {

        $product = commerce_product_load($result->product_id);

        $form[$product->title] = array(
            '#type' => 'fieldset',
            '#title' => $product->title,
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
            '#tree' => TRUE
        );

        $form[$product->title]['cumul'] = array(
            '#type' => 'checkbox',
            '#title' => t('Cumulative'),
            '#required' => FALSE,
        );

        $value = variable_get($product->title, 1);

        foreach ($types = product_node_limit_types() as $type) {

            $form[$product->title][$type['type']] = array(
                '#type' => 'textfield',
                '#title' => $type['name'],
                '#size' => 10,
                '#maxlength' => 10,
                '#required' => FALSE,
                // '#attributes' =>array('placeholder' => ($value[$type['type']] != '') ? $value[$type['type']] : 0),
                '#element_validate' => array('element_validate_integer_positive'),
                '#default_value' => ($value[$type['type']] != '') ? $value[$type['type']] : 0,
            );

        }

    }

    return system_settings_form($form);

}

```

This gives me a form but when I submit it I got an error (the inputs are not recognized as integers even if I put integers in them) , and when I dump the $form\_state after validation, the \['#values'\] index has no values (and the \['#input'\] index has the good values). So Drupal doesn't save the values to the variable table.

I dumped the $value and it was empty, and when I put 7 in the '#default\_value' index, $value got 7. I think the issue is in the default\_value index.

I checked on the stack and found a topic just like this but the answer didn't helped me at all .

How comes the \['#values'\] stays empty ?

Here is the menu\_hook I did

```
function product_node_limit_menu(){

    $items = array();

    $items['admin/commerce/config/product_node_limit'] = array(
        'title' => 'Product node limit',
        'description' => 'Exemple de configuration ',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('product_node_limit_admin'),
        'access arguments' => array('administer site configuration'),
        'file' => 'product_node_limit.admin.inc',
        'type' => MENU_CALLBACK,
    );

    return $items;
}

```

# Answer
> 2 votes
OK the solution was so simple it makes me cry : 'DO NOT PUT SPACES IN THE $FORM ARRAY KEYS'.

It works like a charm since I replaced ' ' by '\_' in the array keys. I feel so stupid ...

# Answer
> 0 votes
The value which u are accessing in default value, always set conditions to 0, so which Drupal considers not be a positive Integer.

What u can do is:

```
'#default_value' => (variable_get($type['type']) != '' )?variable_get($type['type']):0,

```

It will not give u error, and will show your values when it is saved.

---
Tags: 7, commerce
---


title: Upload Image with comments under forums

text:
# Question
Title: Upload Image with comments under forums
In drupal 7 Forums under some topic I want to add a upload image field with the comment field. How can i achive this?

# Answer
> 1 votes
# Install **CKEditor**

> This module will allow Drupal to replace textarea fields with the CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This HTML text editor brings many of the powerful WYSIWYG editing functions of known desktop editors like Word to the web. It's very fast and doesn't require any kind of installation on the client computer.

# As mentioned by darol100, for Upload Install IMCE

> IMCE is an image/file uploader and browser that supports personal directories and quota.

### Here is a nice video tutorial: Installing and Using CKEditor and IMCE

# Answer
> 0 votes
If you are looking for image captions, Here are couple of modules to do that..

**Image Field Caption**

> Adds an extra text area for captions on image fields.
>
> Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

**Image Caption**

> This module uses JQuery to dynamically add captions to images. The image title attribute is used to create the caption. It basically wraps the image in an html container div, takes the image title text and appends that in a child div underneath the image. Technically, it works by implementing Drupal's hook\_nodeapi to add one small snippet of captioner jquery to the head section of the page when a node of the configured type is viewed.

---
Tags: media, comments, nodes
---


# Question
Title: How to check if file has changed during (hook) form_validate in a form?
I have a custom content type, and the relative form for creating/editing contents. It contains a file field. I need to check, during hook

```
 function mymodule_myform_form_validate($form, $form_state){...}

```

if the user changed the file with another (while editing the content). This can be done by checking if the fid has changed, and the fid of the *new* file can be found, for example, in

```
 $lang_field = $form['my_field']['#language'];
 $file_fid = $form_state['input']['my_field'][$lang_field][0];

```

but what about the fid of the old file? Exploring form and form\_state array i found several occurrences of the old and the new fid, but i am not sure which i'm supposed to use. I am not even certain that the code above is the correct one for retrieving the fid of the new file... There is a standard (safe) way to retrieve these informations?

# Answer
Finally i found an explanation of the form\_state array here

form\_state

Unfortunately is not so complete... better than nothing.

To get the fid of the new file i did

```
$lang_field_package = $form['my_field']['#language'];
$fid_new = $form_state['values']['my_field'][$lang_field_package][0]['fid'];

```

> **values**: An associative array of values submitted to the form. The validation functions and submit functions use this array for nearly all their decision making. (Note that #tree determines whether the values are a flat array or an array whose structure parallels the $form array. See Form API reference for more information.) These are raw and unvalidated, so should not be used without a thorough understanding of security implications. In almost all cases, code should use the data in the 'values' array exclusively. The most common use of this key is for multi-step forms that need to clear some of the user input when setting 'rebuild'. The values correspond to $\_POST or $\_GET, depending on the 'method' chosen.

This has proven safer than 'input'. Using 'input', when the user chose a file without pressing the 'upload' button beside the file field, the fid was retrieved as zero instead of the chosen file fid, while in 'values' the fid was correct. It does make sense, but, whether you press upload or not, the file would be load on submit, so i required the right fid anyway.

To get the fid of the old file i did

```
$lang_field_package = $form['my_field']['#language'];
if (!empty($form_state['build_info']['args'][0]->my_field)) {
  $fid_old = $form_state['build_info']['args'][0]->my_field[$lang_field_package][0]['fid'];
}

```

> **build\_info**: Internal. An associative array of information stored by Form API that is necessary to build and rebuild the form from cache when the original context may no longer be available: **args**: A list of arguments to pass to the form constructor.
> 1 votes

# Answer
There are 2 approach we can look into:

1. Query the DB using db\_query in field table, like if your field machine name is field\_image, then its field will be field\_data\_field\_image, and get fid of a particular node, in this case fid will be in field\_image\_fid

SELECT field\_image\_fid from field\_data\_field\_image WHERE entity\_id=NODE\_ID

It will get u previous fid, and u can validate

2. Load Node from nid, either using node\_load or entity\_load\_single, from here you will get your Old FID, as image has not yet been attached to the node, it has only been saved in file\_managed Table.
> 1 votes

---
Tags: forms, files
---


# Question
Title: Adding 'AddThis' sharing functionality to a Drupal Commerce Checkout page
How can you add the 'AddThis' sharing buttons to a Drupal Commerce checkout page?

I tried adding an AddThis field to the product content type as I do for the other content types to wish I want to add this module but that doesn't seem to add it to all the pages in the Drupal Commerce checkout process.

If anyone knows how to do that that would be great. Thanks!

# Answer
> 2 votes
As you discovered in your comment, the recommended approach would be to have the AddThis block show up on the `checkout/*` pages. The question is: what are you sharing, exactly?

If you're wanting to include the sharing process as part of checkout, a new, custom pane would be the best place for this.

---
Tags: commerce
---


# Question
Title: How to enable tag moderation using rules?
I would like to create a rule where if a user adds a tag(taxonomy) which is not allowed (e.g. 'Sexy') the content which contains that tag is sent to be moderated to the site admin for approval before being published. I am currently stuck on the data selector part as I do not know what to put there!

# Answer
I think this module Content Moderation is help to create rules

> * Some selected group should first review those changes (based one a specific revision marked for "approval). In the meantime others
> should be able to edit and create new revisions (which are not part
> of this approval process)
> * Later some group can approve that revision and make it the new live-version
> * Every state change (review, approval..) should get logged in a history. You always want to know, who reviewed / approved what, when
> and what revisions
> * You want to have a different workflow, like some other states between review and approve and live. You want to define your own workflow.
> * You want to create ToDo list for you reviwer / approval teams
> 1 votes

---
Tags: 7, nodes, taxonomy-terms, rules
---


title: How to compress external images?

text:
# Question
Title: How to compress external images?
I load external feeds and i show thumbnails from external links.

I have big problem with Google PageInsight.

Images are not in my server, they are links from feeds. How can I compress those images from feed ?

# Answer
Actually darol100 is right. Since images are not on your server you cannot compress them. But you are able to cache them localy with image cache.

See this article here https://www.drupal.org/node/251009
> 3 votes

# Answer
> How do i compress external images?

**That is impossible.**

You could get the image into your server compressed and the server the image from your server but you cannot compress an external image.
> 0 votes

# Answer
It is possible in some cases to compress external images with Drupal.

There are third-party services, like Imgix, that will compress/resize images on the fly. Typically, these come from an S3 bucket, but some also work from arbitrary URLs. In the case of arbitrary, external URLs, there is usually an authentication method to ensure you have permission to alter the images.

To use these, there are a few options. One would be to use a `hook_url_outbound_alter()` to rewrite the URL to use the third-party service. This is how the CDN module serves up images from an edge cache.

For images added to textfields (eg, images inserted into the body), you would use the Filter API to rewrite the URL to use your third-party service, and then add the filter to your input formats.

And lastly, if your external image is in a field by itself, you can simply write a field formatter to use the third-party service.
> 0 votes

---
Tags: media
---


title: Multilingual content Migration

text:
# Question
Title: Multilingual content Migration
I have Multi-Language website, I need this website to migrate new Drupal website.

I can use node export module for export the content; however, I have a multi-language site, how should I handle those translation nodes ?

# Answer
> 1 votes
It is much easier to create an xml view of your content in each language and import it with feeds module and xpath. Or if it is easier for you, you can export to csv with views data export and import to your new drupal with feeds csv parser. It is much easier and more reliable as you have total control of your content. Though be careful with the delimiters if using csv. XML is safer.

---
Tags: views, i18n-l10n
---


# Question
Title: Varnish has no SSL support; then what to use?
As the developer of Varnish, Poul Henning, wrote back in 2011 on https://www.varnish-cache.org/docs/trunk/phk/ssl.html and again this year on https://www.varnish-cache.org/docs/trunk/phk/ssl\_again.html Varnish has and will have no SSL support.

If this is true for Apache servers (note https://www.digitalocean.com/community/tutorials/how-to-configure-varnish-cache-4-0-with-ssl-termination-on-ubuntu-14-04 has instructions on how to configure both on Nginx), then I wonder what are Varnish alternatives for Drupal sites that need to be running through HTTPS (like, for example, Drupal Commerce sites)?

# Answer
> 2 votes
Content delivery platforms like CloudFlare and Fastly offer a wide range of SSL/TLS options. The question is, what are you trying to accomplish? Note that Varnish really won't do you any good for high transaction-volume sites because you're dealing with authenticated traffic. However, services like the ones listed above can be useful for delivering assets or for serving anonymous traffic.

# Answer
> 0 votes
It all depends to what you want to do. Look at this tutorial here https://www.digitalocean.com/community/tutorials/how-to-configure-varnish-cache-4-0-with-ssl-termination-on-ubuntu-14-04

and here http://blog.ajnicholls.com/varnish-apache-and-https/

---
Tags: commerce, proxies, ssl
---


# Question
Title: Form error messages appearing in the middle of the form
I've got a hopefully EASY question. I'm using a Drupal Commerce-based form in my Drupal 7 site. The form has some required fields. When a user clicks the button to 'continue registration' at the bottom, and they hadn't filled out all the required fields, the form, of course, throws error messages in an error block that tells the user certain fields are required.

But the error messages are not showing up in the correct location. Please see the image below. The main error that there are problems with the form is displaying correctly at the top of the form, but then the problems with individual fields are displaying in THE MIDDLE OF THE FORM. Obviously, not ideal.

So, how do I make all the errors display at the top of the page?

I've already checked my tpl file for the page and the $messages variable is at the top.

# Answer
> 4 votes
This is actually due to the way the checkout module has been written (and is in line with recommended best practices for checkout form submission). The idea is to place the actual error message as close to the form element that generated it to reduce confusion in correcting errors on the form. There is no simple way to undo this behavior in the checkout module.

However, the fact that these are appearing halfway down the page is a good thing - what you really need to do is figure out what it is about your CSS that's causing the messages to float weirdly relative to your form elements.

---
Tags: theming, forms, commerce
---


# Question
Title: Exclude Items from Flat Rate Shipping Calculation
I have several product types:
• T-shirts (FlatRate)
• Pins (FlatRate)
• Poker Chips (No Shipping)
• Gift Card (No Shipping)
• Class Registration (No Shipping)

I charge $10 Flat Rate Shipping for all orders under $75.
All orders over $75 are free.
I do not charge shipping for Poker Chips, GiftCards or Class Registration.

I have everything set up and working EXCEPT I don't want to calculate the price of Poker Chips, Gift Cards or Class Registration in the shipping.

So, if the user orders a t-shirt at $20 and a $100 Gift Card, he should still be charged $10 shipping even though his order total is over $75.

I just can't get the flat rate shipping to not calculate the price of the excluded items in the order.

Help!!

# Answer
This a bit of a complex setup and would be best handled by creating a new inline condition offering the ability to compare the order total of line items of a particular product type to some value. That's really what should be done.

However, this can actually be done with Rules. (Doesn't mean that it should, but it *can*!)

How would you do this? Well, you'll need a couple of components and a reaction rule. Go ahead and create a free shipping discount with Discounts and then modify the rule that gets created. You'll need to disable the Free shipping action and replace it with something that looks like this: **Note that you can't skip the creation of the discount altogether because it's still needed to apply the discount itself (it's down at the bottom in the final rule).**

```
{ "commerce_discount_rule_discount_free_shipping_for_75" : {
    "LABEL" : "Free shipping for $75",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Discount", "Order discount" ],
    "REQUIRES" : [ "rules", "commerce_discount" ],
    "ON" : { "commerce_discount_free_shipping" : [] },
    "DO" : [
      { "component_rules_amount_of_hats_on_order" : {
          "USING" : { "order" : [ "commerce-order" ] },
          "PROVIDE" : { "aount" : { "amount" : "Amount" } }
        }
      },
      { "component_rules_free_shipping_if_order_total_met" : { "order" : [ "commerce-order" ], "amount" : [ "amount" ] } }
    ]
  }
}

```

This rule has two custom actions on it.

1. The first one calculates the total amount of the hats on an order (I built this on Kickstart 2.x so change to suit your needs). The title of the rule isn't as important as is that you'll need a component to calculate a new total you'll compare against.
2. The second action will be the one that actually does the conditional application of free shipping.

### Calculating a total on a subset of products

To calculate a total, we need to loop through all of the line items on an order, and then, if the line item's product is of a certain type, add it to a running total. Since Rules out of the box doesn't have if statements, we can emulate that using another custom component inside of the loop which will conditionally the current line\_item being inspected add it's value to the running total if our product conditions are met. This *could actually be anything, not just product type*.

```
{ "rules_amount_of_hats_on_order" : {
    "LABEL" : "Amount of hats on order",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "order" : { "label" : "Order", "type" : "commerce_order" },
      "amount" : { "label" : "Amount", "type" : "decimal", "parameter" : false }
    },
    "ACTION SET" : [
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0.0" },
          "PROVIDE" : { "variable_added" : { "running_total" : "Running total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_add_total_amount_of_line_item_to_total_if_product_is_of_ty" : {
                "USING" : { "lineitem" : [ "list-item" ], "total" : [ "running-total" ] },
                "PROVIDE" : { "total" : { "total" : "Total" } }
              }
            },
            { "data_set" : { "data" : [ "running-total" ], "value" : [ "total" ] } }
          ]
        }
      },
      { "data_set" : { "data" : [ "amount" ], "value" : [ "running-total" ] } }
    ],
    "PROVIDES VARIABLES" : [ "amount" ]
  }
}

```

### Conditionally add a line item total to a running total

This is where most of the magic happens. This function is simple but could be expanded to do a lot of cool stuff. Currently, all it does is compare the product type to some value, but it could look at taxonomy terms, other fields... you name it! The gist of this rule is that it just does some comparison and then adds the line item value to the running total if it's met. It functions as an if statement. If the conditions are not met, the value doesn't increase.

```
{ "rules_add_total_amount_of_line_item_to_total_if_product_is_of_ty" : {
    "LABEL" : "Add total amount of line item to total if product is of type",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "lineitem" : { "label" : "Line item", "type" : "commerce_line_item" },
      "total" : { "label" : "Total", "type" : "decimal" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "lineitem" ], "field" : "commerce_product" } },
      { "data_is" : {
          "data" : [ "lineitem:commerce-product:type" ],
          "op" : "IN",
          "value" : { "value" : { "hats" : "hats" } }
        }
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "total" ],
            "op" : "+",
            "input_2" : [ "lineitem:commerce-total:amount-decimal" ]
          },
          "PROVIDE" : { "result" : { "result2" : "Calculation result" } }
        }
      },
      { "data_set" : { "data" : [ "total" ], "value" : [ "result2" ] } }
    ],
    "PROVIDES VARIABLES" : [ "total" ]
  }
}

```

### Conditionally applying the Free shipping

Finally, now that we've gotten the product-subset total amount, we can test against that and then apply our free shipping. Note that this rule will have the comparison of the product total and that's where you'd change the amount to compare against.

```
{ "rules_free_shipping_if_order_total_met" : {
    "LABEL" : "Free shipping if order total met",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_discount" ],
    "USES VARIABLES" : {
      "order" : { "label" : "Order", "type" : "commerce_order" },
      "amount" : { "label" : "Amount", "type" : "decimal" }
    },
    "IF" : [
      { "data_is" : { "data" : [ "amount" ], "op" : "\u003E", "value" : "74.99" } }
    ],
    "DO" : [
      { "commerce_discount_free_shipping_service" : {
          "entity" : [ "order" ],
          "commerce_discount" : "discount_free_shipping_for_75",
          "shipping_service" : "standard_shipping"
        }
      }
    ]
  }
}

```
> 2 votes

---
Tags: commerce
---


# Question
Title: How to get variables of field from a view in twig?
I'm trying to style the title field from a view. So I create this template

**views-view-field--frontpage--title.html.twig**

And when I was trying to see what variables are avaiable in this template level. I decide to add

```
{{ kint() }}

```

And for some reason it showing me this huge error.

```
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: CREATE TABLE {cache_render} ( `cid` VARCHAR(255) BINARY CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.', `data` LONGBLOB NULL DEFAULT NULL COMMENT 'A collection of data to cache.', `expire` INT NOT NULL DEFAULT 0 COMMENT 'A Unix timestamp indicating when the cache entry should expire, or -1 for never.', `created` DECIMAL(14, 3) NOT NULL DEFAULT 0 COMMENT 'A timestamp with millisecond precision indicating when the cache entry was created.', `serialized` SMALLINT NOT NULL DEFAULT 0 COMMENT 'A flag to indicate whether content is serialized (1) or not (0).', `tags` LONGTEXT NULL DEFAULT NULL COMMENT 'Space-separated list of cache tags for this entry.', `checksum` VARCHAR(255) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL COMMENT 'The tag invalidation checksum when this entry was saved.', PRIMARY KEY (`cid`), INDEX `expire` (`expire`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT 'Storage for the cache API.'; Array ( ) in Drupal\Core\Render\RenderCache->set() (line 275 of core/lib/Drupal/Core/Render/RenderCache.php).The website encountered an unexpected error. Please try again later.

```

I think this might be a Drupal 8 bug, but I'm not sure.

So my question are..

* How can I get the variables ? Or at least the field value so I can added wrapper around it.
* In Drupal 8, do you think I went to deep on this template ? I notice that using the theme\_debug functionality I could not see this template suggestion.

# Answer
> 4 votes
If you do kint(), then it will try to output the raw data from the sql query and that is obviously to much for kint.

In this template there is not much going on and so there is not really much you can inspect with kint:

```
function template_preprocess_views_view_field(&$variables) {
  $variables['output'] = $variables['field']->advancedRender($variables['row']);
}

```

You can check the output with

```
{{ kint('output') }}

```

But this will only be the field content.

If you want to put a wrapper around the field, that is no problem, that is, what this twig is used for in most cases:

```
<div class="myfield">{{ output -}}<div>

```

If you want to debug the variables, see what variables are available in the view templates, look in core/modules/views/views.theme.inc and inspect them one by one with kint.

---
Tags: views, theming, 8
---


# Question
Title: How do you turn off clean URLs in the database?
How do I turn off clean URLs in Drupal 8 from the database? What table do I look in and what variable do I have to change?

# Answer
> 3 votes
In drupal 8 this setting has been removed:

'clean\_url' configuration setting removed; clean URLs are autodetected each request

I checked the database, there is really no setting with this name.

---
Tags: database, 8, uri
---


# Question
Title: How do you add remote javascript script with custom parameters?
There are many tutorials on adding js to themes in Drupal 7, but the examples for Omega Sub Themes seem to omit the part about remote scripts, scope and weight:

In the theme `.info` file:

```
scripts[] = js/map.js

```

So how do I specify remote URL, header or footer, and what weight to assign?

```
scripts[] = https://maps.googleapis.com/maps/api/js?key=XXX&sensor=false

```

results in `<script src="&muqqwd"></script>` and even if it did work, I still need it to be in the header.

# Answer
> 2 votes
External javascript files can't be declared inside the `theme.info` file, unfortunately. Inside your template.php file, you'll have to add something like this:

```
<?php
  drupal_add_js('https://maps.googleapis.com/maps/api/js?key=XXX&sensor=false', 'external');

```

# Answer
> 0 votes
Try something like:

```
/**
 * Implements template_process_HOOK().
 */
function template_preprocess_page(&$variables) {

  $element = array(
    '#type' => 'markup',
    '#markup' => '<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=false&libraries=places&key=API_KEY"></script>',
  );

  drupal_add_html_head($element, 'google_maps_js');
}

```

This is based on this post.

---
Tags: 7, theming, javascript
---


# Question
Title: How can I add a menu link with no URL so I can add a FontAwesome icon link?
How can I make dummy menu links with Drupal?

This image explains my use case.

I want to make a 'dummy' menu item, so that when I click it the search panel opens.

This is simple using HTML, but Drupal won't allow me to add dummy links and forces me to add an existing url to content/node.

For search icon I use FontAwesome, so I need to be able to add tags/classes around the link.

# Answer
> 2 votes
The combination of the following modules should work for your use case :

https://www.drupal.org/project/special\_menu\_items

> * User can create a new menu item and place either "\< nolink \>" or "\< separator \>" to the Path field, without quotes.
> * "\< nolink \>" item will be rendered similar to a normal menu link item but there will be no link just the title.
> * You can change HTML tag used for menu item
> * "\< separator \>" item will be rendered to an item which is no link and by default title will be "-------".
> * Breadcrumb of "\< nolink \>" will be rendered same as "\< nolink \>" menu item.
> * CSS class "nolink" is added to "nolink" menu item.
> * CSS class "separator" is added to "separator" menu item.

https://www.drupal.org/project/menu\_attributes

> You should use this module when
>
> *You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
You want to give a menu item an ID so you can easily select it using jQuery
You want to add additional classes
or styles to a menu item*
>
> The module currently allows you to set the following attributes for each menu item:
> *Id, Name, Target, Rel, Class, Style, Accesskey*

you would first create a nolink menu with css id or class and then apply your fontawesome css and script to open your search field on click.

# Answer
> 0 votes
You need to write that with js and css file. Here some example.

Search button animation

or maybe this

Expanding text box/button

What version of drupal you use..? Drupal 7 or Drupal 8..?

# Answer
> 0 votes
This sounds like you something the Special Menu Items module is designed for.

But for a more flexible solution, you may want to avoid using the GUI for creating your menu icons, and instead write some custom code that inserts your dummy menu link (which can just link to "#" for example).

There are some other examples and solutions to your issue at this other Drupal Answers thread, including links on using hook\_menu\_alter() in your custom solution.

Any animations or hiding/showing of the icon and the search bar will need to be created by you using javascript/jQuery.

---
Tags: 7
---


# Question
Title: Why is langcode in configuration files ignored during installation?
I have noticed that if I install Drupal in language other than English any config that will be imported during installation will be assigned to that language no matter what language is set in the config itself (the langcode value).

This results in a strange fact that my English config is showing up as XY language and if I enable English I can translate this config only into English, which does not make sense.

So how is Drupal 8 supposed to be installed properly when it comes to i18n?

Currently I am installing in English, and in last step of installation process I add my desired language and set it as default. But that seems like odd thing to be required in order for Drupal to work "properly".

# Answer
> 2 votes
It has to work like this. The alternative would be that a single-language non-English site would need to use the configuration translation to translate its configuration.

For the *en* langcode configuration, the installer will attempt to override it with the provided locale translations, from localize.drupal.org or local, and store the original English configurations separately, as far as I know. So, if you install in a language where you have translations, it should use them; if you don't, you have to change your configuration to the desired language.

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


# Question
Title: How to make metatags output proper images urls
I'm tring to create set of open graph tags for better sharing of my page. Unfortunatelly I cannot make Metatags output proper path to images attached to nodes. I have node with field\_promoted\_image. In metatags configuration I put: \[node:field-promoted-image\] \[node:field-promoted-image:file:url\] \[node:field-promoted-image:file\]

but all I get is field name or file name but without proper path.

# Answer
if you get the file name with \[node:field-promoted-image:file:url\] just put the right path bevore the token. yoursite.de/thepathtoimage\[node:field-promoted-image:file:url\]or maybe you can put the base path token before it
> -1 votes

---
Tags: meta-tags
---


# Question
Title: Is there any way to restore deleted core block in Drupal 8?
How to restore core/menu or other programmatically created blocks if they have been deleted in D8?

I remember in D6 and D7 was no possibility to delete programmatically created blocks. But D8 allows to delete any block. If I delete custom block, I can create it again manually, but if I delete for example Page Title block, there is no way to return page title block to my site.

# Answer
If you delete some code block in /admin/structure/block

You just need to go on **Place block** and add block again.

Also Page Title block you can delete and return like this.

In drupal 8 every think is block, menu even a page title.
> 3 votes

---
Tags: blocks, 8
---


title: Book navigation block?

text:
# Question
Title: Book navigation block?
Where is the book navigation block in Drupal 8?

The structure guide for Drupal 7 says you just need to turn the navigation menu on by enabling the block.

> ...One navigational aid you can use is the book navigation block, which you can enable on the blocks page administer \>\> site building \>\> blocks (Drupal 5 and 6) or Dashboard \>\> Structure \>\> Blocks (Drupal 7). Enabling this block will turn on a menu that shows where the user is in your book; the menu is only visible when viewing the book.

But there doesn't appear to be a "book navigation block" in Drupal 8 as far as I can see.

Where is this block hiding in Drupal 8?

# Answer
You need to click on one of the "Place Block" buttons displayed beside all the region names, a popup with all the unused blocks appears and you select it from the list to add it.
> 0 votes

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


title: JS and CSS image path

text:
# Question
Title: JS and CSS image path
Do I need to hardcode the image path to JavaScript and CSS files?

```
#mydiv { background: url(http://example.org/themes/mytheme/image/bg.png); }

```

I cannot use `{{ base_path }}/image/bg.png` in .js and .css files, which works in a template file.

Is there better way than hard-coding?

# Answer
If I understand correct, no need to hardcode images: Add any image through the Drupal program itself via the API or background images via the css and a relative path:

For example, if your image is at theme/images, do `{background: url(images/image.png);}` or `{background: url(../images/image.png);}` if your css is situated in a folder of it's own inside the theme's folder.

You could filter or manipulate specific images with JS globally via a custom js file for your site as explained here.
> 2 votes

---
Tags: theming, 8
---


title: Replacement patterns for form fields

text:
# Question
Title: Replacement patterns for form fields
I have a drupal commerce form and I'd like it to send me an email with all the data from the form the user filled out every time they submit the form.

Is this possible?

# Answer
> 2 votes
Not sure what a "drupal commerce" form is. There are two major kinds of forms in Drupal Commerce, including the add-to-cart form and the checkout form. Both forms include actions in the Rules module that would let you send an email should one of them get submitted.

Here's a rule that proves the point for add-to-cart (though I would not recommend spamming yourself this way):

```
{ "rules_spam_yourself" : {
"LABEL" : "Spam Yourself",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"DO" : [
  { "mail" : {
      "to" : [ "site:mail" ],
      "subject" : "Product added!",
      "message" : "\/\/ Product\r\nProduct Added: [commerce-product:title] ([commerce-product:sku])\r\nQuantity: [quantity:value]\r\n\r\n\/\/ Order\r\nOrder ID: [commerce-order:order-id]\r\nOrder Number: [commerce-order:order-number]\r\n\r\nOrder Status: [commerce-order:status-title]\t\r\nOrder State: [commerce-order:state-title]\r\n\r\nCreated: [commerce-order:created]\r\nUpdated: [commerce-order:changed]\r\n\r\n\/\/ Customer\r\nCustomer Email Address: [commerce-order:mail]\r\n\r\n\/\/ Actions\r\nCustomer View: [commerce-order:customer-url]\r\nAdministrative View: [commerce-order:admin-url]\r\n",
      "language" : [ "" ]
        }
      }
    ]
  }
}

```

---
Tags: forms, commerce
---


# Question
Title: Is there a way to use a file field without having to upload the file when creating the content?
I’m using Commerce File module for creating mp3 products. I’ve been unable to create a bulk feeds importer because of having to upload the files. Is there a way to simply add the file name when creating these products? The files would have already been put on the server.

# Answer
> 2 votes
You should be able to give it a filename of `public://...` and use that. Just point it to the file you've uploaded.

---
Tags: entities, commerce, files
---


# Question
Title: Is there any other way to create a "settings" node without having to create a Content Type?
I need to create something like a node with settings. This will have custom fields, images, etc... Just like a content type, but without having to create one of them.

Why? I think it's strange having to create a content type when I need to create only one node with that structure.

I know this sounds weird, but just wonder if there is another way?

Thanks

# Answer
The clean way is to create a custom module or theme with settings you need. Examples For Developers shows you how to do it.

If you need settings, you need them because *something* will use them. So just adding a proper form shouldn't be too big overhead. And if you keep your settings in a way that makes possible for field to cease existing, you need to add more lines of code to safeguard against such situations. You don't want that. It's disaster waiting to happen.
> 4 votes

---
Tags: 7, nodes, entities
---


# Question
Title: How to prevent applications from uncovering the technologies used on the website
Here is a super hard question, probably for the most experienced people:

**Can we prevent applications from uncovering the technologies we are using.**

We all know that making sure to keep the core and contributed modules up to date is one of the most important aspect of web development. But meanwhile hiding information about the used technologies will another layer of the security.

Looking in the https://drupal.stackexchange.com/ and Google I can see the last time people talked about this topic was 2013, I think this is the time to ask this question again with hope that someone now have a solution for this.

# Answer
Making all the Drupalisms disappear is hard work and most definitely not worth your while, as stated above by Clive. In addition, you'd also have to edit/obfuscate many of your http headers.

At that point, if it were me visiting your site all the SSL and Trustee certs could not make up for trust lost and I'd leave. Plus, I might tell my nerd friends what a suspicious weird site you run and turn them off too.

My advice: Don't break what makes the web work, and secure your site. You can and should stop nginx and PHP from advertising their version numbers, and you should delete Drupal's .txt files.
> 1 votes

---
Tags: 7, hooks, security
---


# Question
Title: Ckeditor changes <button> tags to <p> tag
Trying to get a button working in content item but ckeditor won't let me.

I tried pasting in source. But when toggling back and forth bewteen source and rich text editor the html changes.

Goes from:

```
<button>click</button>

```

To

```
<p>click</p>

```

I've tried:

```
<p><button>click</button></p>

```

Not working either.

This never happened before, a settings thing?

# Answer
> 0 votes
This is Drupal bug that has been around for years, not even fixed in Drupal 8.

I deleted a text format, disable = delete, not disable, only way to get it back is through PHPmy admin and set to true and false...

Solution:

DON'T TOUCH TEXT FORMATS!

Anybody correct me if I'm wrong, but that's the conclusion I came to.

# Answer
> 2 votes
For **FILTER HTML** go to:

> /admin/config/content/formats/filtered\_html

add `<button>` to the limit allowed HTML Tags list.

If you use **FULL HTML** the button should work.

## **If not try**

go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.

# Answer
> 1 votes
U will have to change above settings, for all text format like: filtered\_html, full\_html. After that clear your website cache, and it will work.

> /admin/config/content/formats/filtered\_html
>
> /admin/config/content/formats/full\_html

---
Tags: wysiwyg, input-formats
---


# Question
Title: Display Date field in email body with rules module
On this page I have a ***registration form***. The ***registration form*** is send to an e-mail address with Rules module.

The related event (Content type 'Event') has a Date field (Wanneer/When), the Date of the event.

How do I display the Date field in the e-mail body? When I put `[entity-fetched:field-event-date]` in the e-mail body, it's not displaying any Date?

# Answer
> 0 votes
i had a wrong date field. It should be `entity-fetched:field_event_date`. Now its working.

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


# Question
Title: Multilingual menus: logic and architecture
A question dedicated for developers: What is the right **Multi-lingual** option for entities and menus in Drupal 8? In contrast to Drupal 7 that never asked me for a menu language, some entities and menus in Drupal 8 asks me for a default... But... I don't want a singular language for that menu... I want it to include 2 and even 3 languages... Thus what is the logical option? My question is basically comprised of two questions:

1. Is it **Not specified**? Or **Not applicable**?, and what is the difference between the two?
2. I also wonder why the ready-to-work menus that comes with the Drupal 8 installation, are not multilingual and are locked to the language in which the site was installed... Won't it be more flexible to set it to some kind of a multilingual option and that's it?...

# Answer
It seems to be impossibe to have one multilingual custom menu in Drupal 8.0.

What you have to do is to create one menu per language. You specify the one language of the menu as you show in your image.

Then in blocks you place all your menus in the same place. Here you can choose which menu is chosen for which language.

This is far from elegant, since you have to edit each language separately without a translate button. But apart from being a cluttered process to create, it works nicely.
> 0 votes

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


title: How to make Redirect Extension

text:
# Question
Title: How to make Redirect Extension
I am creating website which will redirect to the user/login before to see the content since I am using Anonymous Redirect module.

Also, I'm using the Commerce module, so with that, I have one problem. When I want to checkout anonymously, it redirects me to the login page. How can I extend this checkout process to add product before login?

**Example:** When I add "example.com/product/someproduct" it's redirecting me to the login page without checkout button, cant see the products.

Thank you for your time.

# Answer
> 0 votes
I have changed the module to Required Login and repair my problems, thank you.

# Answer
> 3 votes
Note that since you are requiring that anonymous traffic not see content, then product pages would be protected as well, making anonymous checkout impossible without some monkeying. You would likely need to bypass the anonymous redirect on product pages OR create a url that passes a product id to the anonymous user's cart (it would create one if it doesn't exist) and then redirects to the checkout. This would be possible with a rule running on bootstrap, but does have performance implications.

https://www.youtube.com/watch?v=6Rn7FLFytTU is the video where I walk you through this using rules.

# Answer
> 0 votes
Use Checkout login step module to provide option for without login.

---
Tags: commerce, redirection
---


title: Show a ctools modal after form submit

text:
# Question
Title: Show a ctools modal after form submit
I have a form:

```
//...
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Sumbit'),
);

```

I need when this form is validated and submitted then show a ctools modal.

This is my hook\_menu for the modal:

```
$items['thankyou/%ctools_js'] = array(
    'title' => 'Thank you',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'page callback' => 'thankyou_callback',
    'type' => MENU_CALLBACK,
  );
ctools_include('ajax');
ctools_include('modal');

ctools_modal_add_js();

```

The callback function:

```
function thankyou_callback($js = NULL) {
  // Content that we place in the popup.
  $popup_content = t('Thank you!');

  if (!$js) {
    return $popup_content;
  }

  ctools_include('modal');
  ctools_include('ajax');

  $output = array();
  $output[] = ctools_modal_command_display(t('Greetings'), $popup_content);

  print ajax_render($output);
  drupal_exit();
}

```

My form submit:

```
function myform_submit($form, &$form_state) {
  // ...
  // show my modal here
  modal.show();  // ???
}

```

Then, How I show a ctools modal after form submit?

Please, with not ajax callback.

# Answer
You need call form to Popup by function ctools\_modal\_form\_wrapper

Any error, message will show in popup, to check submit success you need use statement

```
if (!empty($form_state['executed'])) {
    $output[] = ajax_command_replace('#modal-content', 'Thank you');
}

```

Or you can use ajax form to call ajax.

```
$form['markup'] = array(
    '#markup' => '<div id="pop-up"></div>'
  );
//You need markup for wrapper
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Sumbit'),
    '#ajax' => array(
      'wrapper' => 'pop-up',
      'callback' => 'modal_form',
    ),
  );

```

And function submit form

```
function modal_form($form, &$form_state) {
  //Process data when form submit
  ctools_include('modal');
  ctools_modal_add_js();
  $commands = array();
  $commands[] = ctools_modal_command_display('Form Submit', 'Say Thank You');
  print ajax_render($commands);
  exit;
}

```
> 1 votes

---
Tags: 7, chaos-tool-suite, forms
---


title: Custom date format in email body

text:
# Question
Title: Custom date format in email body
I have a confirmation email. In the confirmation email i print the Date of the event (Date field) in the e-mail body by `[entity-fetched:field_event_date]`.

This is working fine but the Date is printed like `2016-04-13 16:30:00 to 2016-04-13 20:00:00`

How do i print a custom Date format like i.e. `09-Jan-2016` in my email body?

# Answer
> 2 votes
\[Updated\] You will need to have the Token and Entity Token modules enabled. Then you'll print custom date format with the following token

```
[entity-fetched:field-event-date:value:custom:d-M-Y]

```

the token should produce the date in the format

```
09-Jan-2016

```

refer to PHP Manual for custom date formats.

---
Tags: 7, datetime, emails
---


title: Add Taxonomy Tags to uploaded images

text:
# Question
Title: Add Taxonomy Tags to uploaded images
Is there any way to add the taxonomy term reference (tags) for each image uploaded? It just has 'alt tags' and title as default...

So far I can just add tags for a set of images (albums) but I want to be able to tag each of the images separately - one by one.

# Answer
You can achieve your requirement by installing and configuring Taxonomy Image module.

> The taxonomy\_image module allows site administrators to associate images with taxonomy terms. With the association created, an admin can then make a call to 'taxonomy\_image\_display()' from their theme or other PHP code to display the appropriate image.

Please follow this link as well.
> 0 votes

---
Tags: 7, views, nodes, taxonomy-terms, media
---


# Question
Title: How to use Webform's summed result in another node or block?
First-timer here, a little background: I'm a pretty seasoned builder using tons of modules, but not a developer. Want to start diving into PHP-coding, just not that far yet. Please keep that in mind if you'd be so kind to answer... For now, there's something I want done.

I use the Webforms-module to gather registrations for an event. One of the fields on the form is numerical and holds the amount of persons registering. Works great. Webform gives me a nice analysis in which the submitted values for this field are summed, so I can easily see how many people to expect.

Now I want to use this summed value somewhere else as well. For instance on a page that is accessible by non-authenticated users (as opposed to the Webforms results view, that contains all the personal data I do not want to be public). So I need either some token that I can use elsewhere on the site, or another way of programmatically incorporating that value in a block or a node. Did my share of searching and found a lot, but nothing useful.

I just learned from Klaus Harris' blog how to write a very basic module that can show a page. But how do I get this piece of data where I want it? I took a peek in the webform.report.inc-file that's part of the module, but was rather intimidated by what I saw there...

Is there some way to do this that I can handle without first graduating as a Drupal developer? Or is this too big a jump?

# Answer
It is kind of confusing to create Webform Views with aggregation at first, I'll try to give a detailed explanation.
First, you would create a View of "Webform Submissions" - use unformatted list of fields as format.

Remove all fields that are placed in your View by default.

**Add relationship** to "Webform Submissions: Data" as shown the screenshot below. Adding relationship to webform submission data is crucial for Summing up your field values, because the added relationship gives you an option to add raw value of your field to the View (otherwise SUM aggregation doesnt work - see here). So, you would select your Webform node by typing its ID or the Name of your form, then in "Component Data" drop-down you'll select the field which stores the number that you need to sum up.

**Add the field** to the View scope: Select "Webform submission data: Numeric value(raw)", or " \*: Value(raw)". They both will produce the result that you want. Make sure you select the relationship that you added previously in the field relationship drop-down.

**Enable Aggregation** for your View and set Aggregation to "SUM" on the your numeric field. Watch your field result summed up.

See if this approach works for you.
> 0 votes

---
Tags: webforms
---


title: How do I create custom user tabs?

text:
# Question
Title: How do I create custom user tabs?
I am trying to create a new custom tab that appears on all routes that are descendants of entity.{entity\_type}.canonical. I have tried extending the DeriverBase class, specifically overriding the getDerivativeDefinitions method. I created the tab itself by extending LocalTaskDefault and overriding the getRouteParameters method. The tab appears when you visit a standard Drupal user path such as www.mysite.com/user/1/ or www.mysite.com/user/1/edit. However, when we add our new custom user routes such as www.mysite.com/user/1/subscribe, no tabs appear. Is there a special way to define local menu tasks on custom routes? A sample of the code:

```
 $this->derivatives['recurly.subscription_tab'] = [
  'title' => $this->t('Subscription'),
  'weight' => 5,
  'route_name' => 'recurly.subscription_list',
  'base_route' => "entity.$entity_type.canonical",
];

foreach ($this->derivatives as &$entry) {
  $entry += $base_plugin_definition;
}

```

Thanks in advance of any help.

# Answer
> 7 votes
As suggested by Berdir you can look at Devel module and at how it's implementing that. The following code was "extracted" from Devel

1) Create the routes

Create the file mymodule.routing.yml in and inside define a route callback (which is used for create the dynamic routes)

```
route_callbacks:
  - '\Drupal\mymodule\Routing\MyModuleRoutes::routes'

```

Create the class MyModuleRoutes for generate yours dynamic routes in src/Routing

```
<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class MyModuleRoutes implements ContainerInjectionInterface {

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function routes() {
    $collection = new RouteCollection();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $route = new Route("/mymodule/$entity_type_id/{{$entity_type_id}}");
        $route
          ->addDefaults([
            '_controller' => '\Drupal\mymodule\Controller\MyModuleController::doStuff',
            '_title' => 'My module route title',
          ])
          ->addRequirements([
            '_permission' => 'access mymodule permission',
          ])
          ->setOption('_mymodule_entity_type_id', $entity_type_id)
          ->setOption('parameters', [
            $entity_type_id => ['type' => 'entity:' . $entity_type_id],
          ]);

        $collection->add("entity.$entity_type_id.mymodule", $route);
      }
    }

    return $collection;
  }

}

```

2) Create the dynamic local tasks

Create the file mymodule.links.task.yml and inside define a deriver

```
mymodule.tasks:
  class: \Drupal\Core\Menu\LocalTaskDefault
  deriver: \Drupal\mymodule\Plugin\Derivative\MyModuleLocalTasks

```

Create the class MyModuleLocalTasks for generate yours dynamic routes in src/Plugin/Derivative

```
<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyModuleLocalTasks extends DeriverBase implements ContainerDeriverInterface {

  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = array();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $this->derivatives["$entity_type_id.mymodule_tab"] = [
          'route_name' => "entity.$entity_type_id.mymodule",
          'title' => t('Mymodule title'),
          'base_route' => "entity.$entity_type_id.canonical",
          'weight' => 100,
        ] + $base_plugin_definition;
      }
    }

    return $this->derivatives;
  }

}

```

3) Create the controller

Create the class MyModuleController in src/Controller

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;

class MyModuleController extends ControllerBase {

  public function doStuff(RouteMatchInterface $route_match) {
    $output = [];

    $parameter_name = $route_match->getRouteObject()->getOption('_mymodule_entity_type_id');
    $entity = $route_match->getParameter($parameter_name);

    if ($entity && $entity instanceof EntityInterface) {
      $output = ['#markup' => $entity->label()];
    }

    return $output;
  }

}

```

---
Tags: 8
---


# Question
Title: theme_preprocess_node function not getting executed from template file
I am trying to print action "tabs" in my node.tpl.php file. I added the preprocess function as below-

function MYTHEME\_preprocess\_node(&$variables, $hook) {

```
 $variables['page_tabs'] = menu_local_tabs();

```

}

Then trying to print in my tpl like below.

```
print $page_tabs;

```

But it is not getting executed at all. Infect the control is not going inside preprocess function when I am trying to exit like below-

```
function MYTHEME_preprocess_node(&$variables, $hook) {

 echo "good bye";
 exit;

```

}

Any help is greatly appreciated. Thanks

# Answer
> 0 votes
For using this hook, u will have to replace MYTHEME with your theme name, like if your theme name is bartik, then your function will be

```
bartik_preprocess_node(&$variables, $hook)

```

After that clear your cache, by going to Configuration \>\> Development \>\> Performance

or just write in url admin/config/development/perfromance

---
Tags: nodes, theming
---


# Question
Title: Facing this error while Acquia Drupal set up
> Parse error: syntax error, unexpected '\[' in /Users/\***/Sites/devdesktop/acquia-drupal-7.41.47.6289/profiles/acquia/modules/sqlsrv/sqlsrv.install on line 10

What can I do to fix this error?

# Answer
Not much info so this is a bit of a guess...

Acquia support PHP versions:

> 5.3.29, 5.4.45, 5.5.30 (default), 5.6.14, 7.0.0 RC2

The error message you're seeing suggests short array syntax isn't understood by the version of PHP that's running, which in turn suggests you're running the 5.3.29 option.

Short array syntax was added in PHP5.4, so in theory to fix you just need to install the software with that version instead of 5.3.
> 1 votes

---
Tags: 7, acquia-dev-desktop
---


# Question
Title: Installed Drupal 8 in English, added Hebrew, deleted English and now site is malfunctioning
I've deleted the English language from the site (testing purposes - long story) and now when I go to certain pages I get 404 errors (even in the page that will allow me to bring it back - `admin/config/regional/language/add`.

I guess adding & enabling the language with Drush-master could be helpful but I didn't find any such commands at drushcommands.com

I also tried the following Drupal 7 drush command variations (and others). None worked:

```
drush dl drush_english
drush dl drush_English
drush dl drush_en

```

Maybe there is a manual way to do so which isn't by the UI or Drush?

Ideas?

# Answer
> 1 votes
My solution is comprised of part1, and part 2:

## Part 1

For some reason, from the moment I deleted the English, each time I went to the pages in the site, including the one I could it bring it back in (`admin/config/regional/language/add`) all of these urls included an "he" (Hebrew) part. For example the add language page was:

```
he/admin/config/regional/language

```

But when I changed the he to en (English) than for some reason I could re-add the English language!

But, even thought it seemed I finished with the problem, another one came in, which I also had to solve:

URL's in the site still redirected with "he" parts even after I deleted the Hebrew language from the language lists, and thus I couldn't even flush all caches from the ui because the URL that instructs cache flushing started with an "he" part.. in the following part 2 I will describe how I solved that:

## Part 2

After I re-added English, and deleted the Hebrew language from the list, I went to the "Detection and selection" tab under "Languaes" at `admin/config/regional/language/detection`, and unchecked there the option **URL:** \`Language from the URL (Path prefix or domain), and than I flushed all caches with Drush (the Drupal CLI) and the problem was solved.

I than re-added Hebrew and setted it default language without any problem; Since I changed it's influence on URL's under the "Detection and selection" tab at the Languages page, I didn't have the "he"\\"en" parts problem after that.

# Answer
> 0 votes
I was having the some problems.

Just don't delete any language.

There is this bag https://www.drupal.org/node/2540876

My sugestion is to save all module and theme, export what you can and instal drupal 8 from begining.

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


# Question
Title: How to have a combined search view that shows both users and content on search terms?
I've looked at multiple modules (Faceted Search, Custom Search, an abandoned project named search\_all) but I haven't been able to find anything that works with 7.x.

What I'm looking for is just a way to let users search on a search term and then get a page of results from all content, including other users in the system.

Any ideas?

# Answer
# There are similar question to yours here:

How do I create a View of different entity types?

How to create a union of two views?

Other than that there are several answers possible:

# Get the data searchable

Attach nodes to the users. Take a look at drupal.org/project/profile2 or http://drupal.org/project/content\_profile (depending on your drupal version).

# Extend search

Other than that the mentioned http://drupal.org/project/search\_api seems like a good place to start.

# Note

You probably know this but in case you (or sb finding that question) doesn't. To search views add a filter called "Search: Search Terms (optional )" and expose it.
> 1 votes

# Answer
Haven't tried it, but I believe you could use Apache Solr with the http://drupal.org/project/search\_api, http://drupal.org/project/search\_api\_solr, and http://drupal.org/project/search\_api\_multi

Create two indexes, one for nodes and one for users. Then create a view that uses both indexes.
> 5 votes

# Answer
This would be an interesting project for sure. If I were to write a module to do this, I would copy the parts before the `execute` call in node\_search\_execute and user\_search\_execute and create `UNION` query out of them. Modify of course the fields selected so they are uniform, I recommend entity\_id and adding an `addExpression('entity_type', 'node')` so that rows can be loaded by `entity_load`. That's... about it. It'll be slow as hell.

Alternatively you can take the UNION query created here and feed it to SphinxSearch and search that.
> 2 votes

# Answer
There is a module called search\_combine that claims to give one set of search results for all content types and users.

However I've installed it and enabled it and permissions it requires and it doesn't seem to make any difference: the results remain separated for content and user.

Just bringing it to your attention in case you'd like to have a go using it (and if you get it working let us all know how you did :) )
> 1 votes

# Answer
thanks for the advice:

the module search\_combine is OK for combining the search results of user and content this is the config way if not found:

1. install activate the module:

```
drush en search_combine -y

```
2. permission: tick all
3. configuration:Administration » Configuration » Search and metadata » search settings:
4. ACTIVE SEARCH MODULES:on select:"Search combine" and untick node and user option
5. on Default search module: select "Search combine" option
6. ```
    drush cc all

```

and everything is alright
> 0 votes

---
Tags: search
---


title: error when updating module

text:
# Question
Title: error when updating module
I'm trying to update my `colorbox` module and I keep getting the error:

> Update failed! See the log below for more information. Your site is still in maintenance mode.

and below it says:

**colorbox**

Error installing / updating *File Transfer failed, reason: Cannot remove directory /home/content/02/12910502/html/sites/all/modules/colorbox/..*

**Next steps** *Your modules have been downloaded and updated. Run database updates*

why do I get this error and how can I get this fixed?

**EDIT1**
I'm using GoDaddy shared hosting. All permissions for files & directories in ftp are set to 755 (owner 12910502) within `colorbox/` but I still get this error... - I've never had a problem on other sites I'm working with, weird.
This is drupal core **7.15** \- may that be the reason?

**EDIT2**
How abut if I just replace the directory onthe ftp with the latest version and then run `update.php`, should this work too?

# Answer
> 2 votes
Sounds like a permission issue.

If you're using ubuntu, make sure the user owner for your modules folder is www-data and 755 permission.

Also, don't forget to run `update.php` by going to `www.yourwebsite.com/update.php` after you update drupal core OR any module.

# Answer
> 0 votes
I ended up upgrading the modules as I suggested in **EDIT2** above. Worked fine except `ctools`, that module is still pending...

---
Tags: updating
---


title: Add checkbox in node menu settings

text:
# Question
Title: Add checkbox in node menu settings
I would like to add one checkbox in Menu settings at node /node/add/{Content types}

I am not sure how to do that. I need to use ***Form and Controller***.

**What form I need to include?** This is some of them.

```
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

```

And after I need to implemente Implements hook\_form\_FORM\_ID\_alter().

**Is my thinking ok?**

# Answer
> 0 votes
If I understand you correct, you want a menu to appear only at a certain content type? It is not done from there.

In Drupal 8 each menu is a block; After you have created the menu regularly with the native API unchanged, just add the block to the desired region and then set that block to appear only in a certain region you want it to appear in (You should see such an option in the block's conf page).

---
Tags: forms
---


# Question
Title: Entity reference views with Exposed filters
I have created a content type Subjects with following fields:

* Student ID
* Subject Title
* Subject Code
* Subject teacher

I have also created an entity form for accepting comments from students about subject they study and subject teachers.

I am trying to create an entity reference view and also want to use exposed filter. Reason for using exposed filter is that I want student to provide his student ID so that subjects which he is studying is updated in a select list. I am unable to achieve this.

I am also using Entity Reference autofill module to display the value of Subject Code and teacher in my entity form. The value of Subject code and teacher will be populated based on Student ID and Subject code. Please note one student will be studying more than one subject

I have already created a few contents of type subjects. My question may appear a duplicate question but I read mostly all answers but nothing is matching my case.

# Answer
> 0 votes
I don't have drupal on me atm to try this out. So consider this an educated guess.

in RELATIONSHIP add student\_id referenced entity and click on force relationship.

Then hope that in filters, there is a new option to add referenced entity.

---
Tags: views, entities
---