title: View discounts for a group type

text:
# Question
Title: View discounts for a group type
I use the "Group" and "Commerce discount" modules to make bundled sales. This is used to display discounts to certain type of group.

I have a group type (company) and group type (flash sale).

I want a 10% discount for the group (company) type on the whole catalog and a 30% discount for the group type (flash sale).

Is it possible to do this ?

Discounts must be applied to the product catalog, as in the screenshot :

Thank you

-10% and -30% are examples, I know how to create discounts. But how to apply the discounts to the group type (company) ?

I want only the members who belong to company sees the discounts.

Here is the export of a discount :

```
{
  "name" : "discount_professionnel_remise_produits_10",
  "label" : "PROFESSIONNEL Remise produits 10",
  "type" : "product_discount",
  "status" : "1",
  "component_title" : "Remise sur les produits -10%",
  "sort_order" : "10",
  "discount_usage_per_person" : [],
  "discount_usage_limit" : [],
  "commerce_discount_date" : [],
  "commerce_discount_offer" : {
    "type" : "percentage",
    "commerce_percentage" : { "und" : [ { "value" : "10.00" } ] },
    "rdf_mapping" : []
  },
  "inline_conditions" : { "und" : [
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "15" } ], "condition_logic_operator" : null },
        "condition_negate" : 0
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "16" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "17" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "18" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "19" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "20" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "21" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "22" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "23" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "24" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "25" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "26" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "27" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "28" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "29" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "30" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "31" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "32" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "74" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "76" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "63" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "64" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "65" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_product_contains_products",
        "condition_settings" : { "sku" : [ { "product_id" : "66" } ] },
        "condition_negate" : 0,
        "condition_logic_operator" : "0"
      },
      {
        "condition_name" : "commerce_discount_extra_line_item_user_has_role",
        "condition_settings" : { "roles" : {
            "utilisateur M2" : "utilisateur M2",
            "utilisateur E1" : "utilisateur E1",
            "utilisateur E2" : "utilisateur E2",
            "administrateur A2" : "administrateur A2"
          }
        },
        "condition_negate" : 0,
        "condition_logic_operator" : "1"
      }
    ]
  },
  "commerce_compatibility_strategy" : { "und" : [ { "value" : "any" } ] },
  "commerce_compatibility_selection" : [],
  "rdf_mapping" : []
}

```

# Answer
You can try with Commerce Discount Extra or use Commerce Discount Product Category modules This modules gives extra conditions in commmerce discount configuration
> 0 votes

---
Tags: 7, commerce, rules, group
---


# Question
Title: Why to use [attributes] when adding class to a button inside my hook function
I request somebody to please explain why I have to use `['#attributes']` when adding one or a combination of CSS `class`-es to the `Submit` button inside a `search-block-form` but when changing just the Text, `['#attributes']` is not required?

To change default text of the button I am writing:

```
function ezone_form_search_block_form_alter($&form, &$form_state, $form_id){
    $form['actions']['submit']['#value'] = t('Search now');
}

```

But when adding a CSS class to the same button I have to write this:

```
function ezone_form_search_block_form_alter(&$form, &$form_state, $form_id){
    $form['actions']['submit']['#attributes']['class'][] = 'btn btn-primary';
}

```

Why although `value` and `class` both are attributes of a button element, I have to do them differently? If I take out the `['#attributes']` part (`$form['actions']['submit']['#class'][] = 'btn btn-primary';`) button classes don't not render.

I Googled but could not find anything specific about it! It would be great if someone can put lights on this. I am a new comer at Drupal platform!

# Answer
This more a theoretical question. You can see in the documentation or example code how to use the render element.

The technical background is, that each render element defines variables which you can use when building the render array. The variables of a render element are placed on the top level of the render array and prefixed with '#'.

This is an excerpt of the code which prepares the render element for rendering:

```
  public static function preRenderButton($element) {
    $element['#attributes']['type'] = 'submit';
    Element::setAttributes($element, array('id', 'name', 'value'));

```

Here you can see that `#id`, `#name` and `#value` are placed in the attributes by the element itself.

If you want to set other attributes, you have to place them yourself in `#attibutes`.
> 1 votes

---
Tags: theming, 8, forms
---


# Question
Title: How To render calendar view header programmatically
I am using Page calendar and I want to print calendar view header in a different block. How can I achieve this?

# Answer
Assuming that you have a `view` of type `page` that shows calendar. But you want that calendar to be rendered in a block. And this block you want in your header.

So, for this, click on `advanced` section in views. There you will see EXPOSED FORM Exposed form in block:No

Click on `No` and make it yes. Check your blocks, a block of this view will get created. Now with the help of `page.tpl.php`, render this block in your header section.

Or simply assign this block to 'header' region if you already have header region managed in your tpl file.
> 0 votes

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


# Question
Title: Why is the chart button missing when trying to create a chart using Easychart?
I have chart content type and chart content.

But when I try to add content I do not see the chart button, as shown in this image also:

# Answer
Have a look at the Easychart support request "Installation on Drupal8". It contains varioous hints about what might be the cause of your issue, such as in these comments in it:

* nr 3: You need to install embed & entity\_embed to get the chart buttons.
* nr 8: I ... didn't have Libraries API module installed.
* nr 8: It appears to look for ec.min.js. The Easychart library that drush installed for me didn't have ec.min.js , but copying ec.full.min.js to ec.min.js makes it all work

**Note**: I added the hyperlink here for the Libraries API (it's the commonly used one, there is no Easychart specific variation of it ... at least not that I'm aware of).
> 1 votes

---
Tags: 8, charts
---


title: twig kint permissions buggy

text:
# Question
Title: twig kint permissions buggy
When debugging with kint in a twig tpl the output is seen also by site visitors although they are not logged in.

Permissions "Access kint information" are set just for admin.

Is this a bug?

# Answer
> 0 votes
Most likely the issue is probably related to caching, you can argue that it's a bug in devel/kint module and that is should have an implementation to handle this.

I would argue that the use of kint in a template file is made for running the site in development mode and if you disable caches (which is a really idea on an actual production site) it should work just fine.

---
Tags: theming, users
---


title: How to render URL ALIAS field on form?

text:
# Question
Title: How to render URL ALIAS field on form?
Is there a way to render the URL Alias field on the form separately from the `print drupal_render_children($form);`?

My plan is to render the URL Alias field on top of the form neatly (before the other fields), bcoz right now its in some sort of box like output that is generated by Drupal.

Any help would be greatly appreciated.

# Answer
> 0 votes
If i understand you in the right way you want to edit path alias when creating new content. At first you have to give permission to create and edit URL aliases to some user role.

Then just add `<?php print drupal_render($form['path']); ?>` to your form template (EG. to the top of the form).

---
Tags: forms, path-aliases
---


# Question
Title: Replace 'page' twig template for controller/url
I have a page generated with custom controller. It's special page, so i need to remove all sidebars, headers and logo, for that page, and use custom design/layout.

How can i replace 'page' twig template for that url/controller?

# Answer
Just create new twig template in the template folder of your theme `page--your-url.html.twig` and clear the cache.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Should I declare the usage of a new template.php file?
I created a *template.php* file, put the following function inside, saved, and flushed all Drupal cache. The desired change didn't occur.

```
function garku_process_html(&$variables) {
  $variables['styles'] = preg_replace('/.css\?.*"/','.css"', $variables['styles']);
}

```

How should I declare the usage of a new template.php file in a Drupal 8 sub-theme?

I ask since I haven't found anything about this in the documentation, for example in Overview of theme files.

# Answer
Drupal 8 themes don't have template.php files. Now they use a *mytheme.theme* file, which needs to be located inside the directory containing the theme. (Replace *mytheme* with the machine name used by the theme.)

Preprocessing and modifying attributes in a .theme file shows an example of preprocess function, which is placed in the *mytheme.theme* file, instead of the *template.php* file.
> 6 votes

# Answer
The file name was changed to \[theme-name\].theme; from the docs:

> **\*.theme**
>
> The .theme file is a PHP file that contains all the conditional logic and data (pre)processing of the output. It may also extend basic theme settings.
> 3 votes

---
Tags: 8, theming
---


# Question
Title: What's the correct way to add attributes to a Link field?
So I'm preprocessing a field: `preprocess_field` and trying to add attributes to a Link. I've tried:

`$variables['items'][0]['attributes']['target'] = '_blank';
 $variables['attributes']['target'] = '_blank';
 $variables['#attributes']['target'] = '_blank';
 $variables['content_attributes']['target'] = '_blank';
 $variables['content_attributes']['attributes']['target'] = '_blank';
 $variables['items'][0]['#attributes']['target'] = '_blank';
 $variables['items'][0]['options']['attributes']['target'] = '_blank';
 $variables['items'][0]['#options']['attributes']['target'] = '_blank';
 $variables['items'][0]['#options']['target'] = '_blank';
 $variables['items'][0]['#content']['#options']['attributes']['target'] = '_blank';
 $variables['items'][0]['#content']['options']['attributes']['target'] = '_blank';
 $variables['items'][0]['#options']['attributes']['target'] = '_blank';`

A silly amount of attempts, none of these worked. How can I add attributes to a link?

# Answer
There were some close ones, but this is the correct way to set an attribute to the first link:

```
function mymodule_preprocess_field(&$variables) {
  if ($variables['field_type'] == 'link') {
    $variables['items']['0']['content']['#attributes']['target'] = '_blank';
  }
}

```
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: How to disable image caption in views block?
How to disable image caption in views block?

The image caption module is image field caption.

I apply it on my Drupal 7.

Enable module and add in caption.

In node, it looks good.

In View Block, it looks like this. How to remove the caption in Views block?

==================================

Add View configuration image

Below is Views setting:

Below is Configure field: Content: Image settings:

# Answer
If you're not picky, a possible alternative quick fix is to just hide it with CSS. This way you don't have to worry about or spend time patching the module.

You can do it like this:

```
.image-field-caption { display: none; }

```

Note that the above will hide all captions, if you only want to hide the captions of a specific view:

```
.view-id-[name] .image-field-caption { display: none; }

```
> 2 votes

# Answer
Given that you use the Image Field Caption module, this is not so easy. The module overrides the default image formatter (the chunk of code that controls how an image field is rendered) and adds its captions. There are two issues in its issue queue on drupal.org to make the module more flexible:

1. Add ability to configure to display the caption based on view mode adds a configuration option to the image formatter, allowing you to choose to display the caption or not.
2. Add formatters for image with caption instead of overriding the default proposes to introduce a separate image-with-caption formatter instead of overriding the default, so you can choose which formatter you want.

I have never tried these patches so I cannot recommend either of them, but you could try them (see the documentation on applying patches) and see if it solves your problem. Both methods should be compatible with Views. I would start with the first option because the code looks a bit simpler and it doesn't require database updates.
> 1 votes

---
Tags: media
---


title: Drupal 8 register link?

text:
# Question
Title: Drupal 8 register link?
I have a clean Drupal 8 install with bootstrap theme. I just want to add a simple link to the registration form in the user account menu and to it only be visible if you are not logged in.

The login and my account links are already standard in, why isnt the register button there? What would be the solution to this?

Creating the link normally in the menu -\> add link option makes it visible all the time.

# Answer
I haven't been able to find a contributed module that might make this easier, so the only other possibility is code.

What you are basically asking for is the altering of an existing route, that was defined by the User module. I'm not sure how much experience you have with the new Drupal 8 architecture and APIs, so I'm going to just dump a few links here :p

The first is the documentation of the new routing system that Drupal 8 is using. The route that you want to change is the one with the path */user/register*, so you will have to look for the route's name and alter it.

A good article about how to do that can be found here. Your use-case is very similar to what the example shows with the *logout* route.

So basically you will have to write a RouteSubscriber that will alter your route, based on the current user's loggedIn status. I'm not at my PC at the moment, so I can't give code example, but if you need, then I can share a solution.

Be advised, that there are lots of new concepts that you will have to understand first, but if you already know Drupal 8, then you will have no problem with the aforementioned solution.

Another possibility would be to hide the link from the theme layer, in a Account Menu's preprocess function.
> 2 votes

# Answer
Why create new route? There is one already! Via admin panel, create new menu item at 'account' menu. Link hidden after login (RegisterAccessCheck class will hide it).

```
fill fields:
name = Register
uri = route:user.register

```

UPDATE1 You will see link as admin, but others - don't
> 4 votes

# Answer
We've contributed a small module which solves this issue: https://www.drupal.org/project/registration\_link
> 3 votes

---
Tags: 8, users, navigation
---


# Question
Title: Integrity constraint violation: 1048 > Column 'entity_id' cannot be null
Whenever I try and create a new node (of type article, page, blog, etc), for some reason I get thrown the following error upon hitting the save button.

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'entity\_id' cannot be null: INSERT INTO {pathauto\_state} (entity\_type, entity\_id, pathauto) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> \[:db\_insert\_placeholder\_2\] =\> 1 ) in pathauto\_entity\_state\_save() (line 492 of /sites/all/modules/pathauto/pathauto.module).

I've tried going into the database and setting these columns to allow NULL, but this doesn't seem to fix the issue. I've also tried uninstalling and reinstalling the pathauto module, but no luck.

This error was occurring previously with a couple of other modules, and I seem to have fixed them. I'm just not sure why this error is occurring at all (e.g. I can edit and save existing nodes, but creating new ones all of a sudden is a problem?)

**UPDATE: Another issue I seem to get:**

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'id' cannot be null: INSERT INTO {file\_usage} (fid, module, type, id, count) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4); Array ( \[:db\_insert\_placeholder\_0\] =\> 126 \[:db\_insert\_placeholder\_1\] =\> file \[:db\_insert\_placeholder\_2\] =\> node \[:db\_insert\_placeholder\_3\] =\> \[:db\_insert\_placeholder\_4\] =\> 1 ) in file\_usage\_add() (line 698 of /includes/file.inc).

# Answer
## Short answer

It sounds like you have some code which deletes the node ID on saved nodes causing trouble.

## Longer answer.

When you create a new node, Drupal will internally make an insert to the `node` table to generate an ID and then use that id to populate `node_field_data` and `node_field_revision` tables (assuming you are using revisions). The ID is also set on the node entity itself and is accessed via the `id()` method on the `Node` class.

The `NodeForm` does a check on the node object upon being saved, and rebuild the form in case the node doesn't get an ID.

Since you don't get an error for `node_field_data` and `node_field_revision` tables, it's pretty safe to assuming that the ID generation works and the node is populated with the ID (Core has lots of test cases covering this).

Since stuff reacting to the node being saved fails, with the missing ID, some code must delete the ID after it's set. Class instances are passed by reference, meaning that if you change one instance you change it every where that class instance is used. So most likely you have some code messing stuff up. There is a good chance that it's some code implementing `hook_entity_insert` or `hook_entity_update` (or the node specific variations of those hooks).
> 3 votes

# Answer
Make sure your database is fully up-to-date (run `drush updb` or visit /update.php). If you have pending database updates you can run into errors like your describing. There are times when errors occur during the update process and you either have to run them a second time, or have to fix another problem before they will run.

Make sure that all updates run successfully and then check the site's status page and make sure nothing is flagged as red.
> 1 votes

# Answer
Here are a few pointers to help solve the issue:

* Are you creating nodes using code anywhere? If yes, then make sure that the node is being saved properly and an ID is being generated for it.
* Can you try creating a node using code and see if the node ID is being generated properly?
* If nothing works, can you try doing another fresh Drupal install on the same server and see if creating a node still throws errors?
* Check if your modules are up-to-date by visiting the `/admin/modules` page and clicking `Check for updates`.
* Check if your schema is up to date. Visit `update.php` and do a database update (or use `drush` if you use it).

Hope it helps. I had faced this kind of a problem once. But in my case, I was attaching files to the node using custom code.
> 1 votes

---
Tags: 7
---


# Question
Title: #upload_validators missing error message
## \[Update\]

Upon further investigation it seems that the message isn't appearing due to the following javascript error:

"Uncaught TypeError: Cannot read property 'length' of undefined"

I'm not sure how to resolve this error, but the following issues may be related:

## Description

I'm trying to create a custom form with some number of file upload fields (for now I'm using the hard-coded value 3).

I have added an #upload\_validators attribute to the managed\_file element that calls file\_validate\_extensions and passes in "doc" as the only valid filetype.

When I try to upload a .jpg, an error appears -- which is what I want. However, the error doesn't contain any text.

Any idea what I'm doing wrong?

## Code

```
function mymodule_example1_form($form_state) {
  $num_docs = 3;

  // Build the number of name fieldsets indicated by $form_state['num_docs'].
  for ($i = 1; $i <= $num_docs; $i++) {
    $form['managed_file'][$i] = array(
      '#type' => 'managed_file',
      '#title' => 'Managed File' . $i,
      '#progress_indicator' => 'throbber',
      '#progress_message' => 'Upload successful!',
      "#upload_validators"  => array("file_validate_extensions" => array("doc")),
      '#upload_location' => 'public://doc/',
    );
  }

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

  return $form;
}

```

## Screeshot

## Resources

# Answer
I was able to resolve the issue using the solution posted here.

As I understand it, the issues is caused by an ID being used more than once. To fix this, you can implement an `#after_build` callback that ensures the upload fields will have unique IDs.

To summarize...

**Add an `#after_build` callback to the `managed_file` field:**

```
$num_docs = 3;

// Build the number of name fieldsets indicated by $form_state['num_docs'].
for ($i = 1; $i <= $num_docs; $i++) {
  $form['managed_file'][$i] = array(
    '#type' => 'managed_file',
    '#title' => 'Managed File' . $i,
    '#progress_indicator' => 'throbber',
    '#progress_message' => 'Upload successful!',
    "#upload_validators"  => array("file_validate_extensions" => array("doc")),
    '#upload_location' => 'public://doc/',
    '#after_build' => array("MODULE_file_managed_fix_duplicate_id"),
  );
}

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

```

**Create the following callback:**

```
function MODULE_file_managed_fix_duplicate_id($element) {
  if ($element['#id'] === $element['upload']['#id']) {
    $element['#id'] = drupal_html_id($element['#id']);
  }
  return $element;
}

```

Once I did that and cleared all my caches, the javascript errors went away and the error messages starting working.
> 1 votes

---
Tags: 7, forms
---


title: Preventing webform save

text:
# Question
Title: Preventing webform save
**Goal**: Using webform (and it's hooks) in drupal 7 I need to, under certain conditions, avoid saving the form submission (i.e. under those conditions I need to discard the submission instead of saving it to submissions models or, if that's not possible, correctly reference the submission and delete it).

**Question**: How is that done? Either of the solutions would be fine for me. I didn't try anything yet, since I have no clue at all about how to do any of them. I can just barely imagine it should be done on \_alter or \_presave hooks, but I'm not sure, and can't find about.

**Current state**: Totally n00b and clueless about.

**Notes**: Assume hooks as:

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    //validations occur here to test whether the current form is a webform node.
}

```

EDIT - **Additional IMPORTANT notes I forgot**: Depending on the value of some fields, I have two possible scenarios:

1. Avoid saving, then redirect (to external URLs, i.e., urls not belonging to my Drupal install. The redirection url must be the result of an evaluated expression, and not just a single url which I could specify in the webform settings).
2. Save, then redirect (to internal URLs, i.e., urls belonging to my Drupal install. The redirection url must be the result of an evaluated expression, and not just a single url which I could specify in the webform settings).

# Answer
> 0 votes
yes hook\_form\_alter is the right hook you are looking for.

Something like below. Please check the values of form field inside $form\_state and fix the code accordingly.

Basically hook\_form\_alter will allow you wo conditionally add submit handler to your webform which means if form field value is Y then only your custom submit handler will call, also the way we adding the custom submit handler is by replacing the other handlers so no conflict with your sudmit handler and any other comes by default.

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
   if($form_id == "your_webform_id") {
     if($form_state['your_form_field']['#value'] == 'Y') {
       $form['#submit'] = 'custom_submit_handler_external';
     }
     if($form_state['your_form_field']['#value'] == 'X') {
       $form['#submit'][] = 'custom_submit_handler_internal';
     }
   }
}

function custom_submit_handler_external(&$form, &$form_state) {
  drupal_goto("redirect to a page");
}

function custom_submit_handler_internal(&$form, &$form_state) {
  $redirect_to = $form_state['redirect_field']['#value'];
  $form_state['redirect'] = $redirect_to;
}

```

The above code is just an idea of how you can approach, please debug it at every step and make it workable for you.

# Answer
> 0 votes
I had the certain scenario where I had to prevent webform save for a particular component namely 'pay' component. I could achieve this with the following code

```
function hook__webform_submission_presave($node, &$submission) {
  $components_list = $node->webform['components'];
  foreach ($components_list as $comp)
  {
   if($comp['type']=='pay')
   {
    $comp_id = $comp['cid'];
   }
  }
 unset($submission->data[$comp_id]);
}

```

---
Tags: 7, webforms, forms
---


title: How can I create a node via ajax call?

text:
# Question
Title: How can I create a node via ajax call?
I have a site where a custom form is in opened in a modal, and when submitted calls an ajax function to POST to a REST service to create a node.

The problem is I keep getting "Forbidden" response upon submission.

I only want logged in users to be able to send these ajax requests and the auth should be different token for each user.

Here is my code:

```
$('#create-node-submit').click(function(e) {
    e.preventDefault();
    var newNode = {
        _links: {
            type: {
                href: 'http://mysite.dev/rest/type/node/article'
            }
        },
        type: {
            target_id: 'article'
        },
        title: {
            value: 'This is a test Article from REST'
        },
        field_description: {
            value: 'Here is some test description.'
        }
    };
    getCsrfToken(function (csrfToken) {
        postNode(csrfToken, newNode);
    });

    return false;
});

function getCsrfToken(callback) {
    $.get(Drupal.url('rest/session/token'))
        .done(function (data) {
            var csrfToken = data;
            callback(csrfToken);
        });
}

function postNode(csrfToken, node) {
    $.ajax({
        url: 'http://mysite.devdev/entity/node?_format=hal_json',
        method: 'POST',
        headers: {
            'Content-Type': 'application/hal+json',
            'X-CSRF-Token': csrfToken
        },
        data: JSON.stringify(node),
        success: function (node) {
            console.log(node);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Status: " + textStatus);
            console.log("Error: " + errorThrown);
        }
    });
}

```

When running a test in POSTMAN it is successful, but the authentication was slightly different there:

As you can see in the picture, I get 201 created when using POSTMAN.

I believe it has to do with the CSRF token being used in the Javascript implementation. I'm not sure what authentication method I'm supposed to use when POSTing to the same site via JS.

I used the information here.

I created a bug report as it seems the CSRF token check passes successfully and grants access, but access is denied from somewhere else. Issue #2831251 Trying to create nodes via REST with ajax POST request returns 403 response

# Answer
> 2 votes
The issue was due to a bug in Rest UI module v.1.13 for D8.

As of writing this, the issue is not resolved on the module, but there is a workaround.

To get around the problem, configs exported from Rest UI need to be adjusted under "authentication".

See here for more info: https://www.drupal.org/node/2831716#comment-11813802

# Answer
> 2 votes
You can use Postman, a Google Chrome browser app that allows you to POST, GET, PATCH, and DELETE to any site (for testing purposes), to generate the code for you:

After completing the 3 steps shown in the picture, you need to perform 1 more step:

4. Then paste the code into your custom module.

**PS:** I believe you can delete the `postman-token` line in the `headers`.

---
Tags: javascript, ajax, 8
---


# Question
Title: Error with link field: "Unrouted URIs do not have internal representations"
I am trying to a menu link to a node and getting this exception:

```
"Unrouted URIs do not have internal representations"

```

Backtrace:

The website encountered an unexpected error. Please try again later.

```
Drupal\Core\Entity\EntityStorageException: Unrouted URIs do not have internal representations. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
token_tokens('url', Array, Array, Array, Object)
call_user_func_array('token_tokens', Array) (Line: 402)
Drupal\Core\Extension\ModuleHandler->invokeAll('tokens', Array) (Line: 304)
Drupal\Core\Utility\Token->generate('url', Array, Array, Array, Object) (Line: 728)
token_tokens('menu-link', Array, Array, Array, Object)
call_user_func_array('token_tokens', Array) (Line: 402)
Drupal\Core\Extension\ModuleHandler->invokeAll('tokens', Array) (Line: 304)
Drupal\Core\Utility\Token->generate('menu-link', Array, Array, Array, Object) (Line: 715)
token_tokens('menu-link', Array, Array, Array, Object)
call_user_func_array('token_tokens', Array) (Line: 402)
Drupal\Core\Extension\ModuleHandler->invokeAll('tokens', Array) (Line: 304)
Drupal\Core\Utility\Token->generate('menu-link', Array, Array, Array, Object) (Line: 1131)
menu_ui_tokens('node', Array, Array, Array, Object)
call_user_func_array('menu_ui_tokens', Array) (Line: 402)
Drupal\Core\Extension\ModuleHandler->invokeAll('tokens', Array) (Line: 304)
Drupal\Core\Utility\Token->generate('node', Array, Array, Array, Object) (Line: 196)
Drupal\Core\Utility\Token->replace('[node:menu-link:parent:url:relative]/[node:title]', Array, Array, Object) (Line: 193)
Drupal\pathauto\PathautoGenerator->createEntityAlias(Object, 'update') (Line: 329)
Drupal\pathauto\PathautoGenerator->updateEntityAlias(Object, 'update') (Line: 114)
pathauto_entity_update(Object)
call_user_func_array('pathauto_entity_update', Array) (Line: 402)
Drupal\Core\Extension\ModuleHandler->invokeAll('entity_update', Array) (Line: 169)
Drupal\Core\Entity\EntityStorageBase->invokeHook('update', Object) (Line: 418)
Drupal\Core\Entity\ContentEntityStorageBase->invokeHook('update', Object) (Line: 470)
Drupal\Core\Entity\EntityStorageBase->doPostSave(Object, 1) (Line: 304)
Drupal\Core\Entity\ContentEntityStorageBase->doPostSave(Object, 1) (Line: 395)
Drupal\Core\Entity\EntityStorageBase->save(Object) (Line: 761)
Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object) (Line: 364)
Drupal\Core\Entity\Entity->save() (Line: 356)
Drupal\node\NodeForm->save(Array, Object)
call_user_func_array(Array, Array) (Line: 111)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object) (Line: 51)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object) (Line: 585)
Drupal\Core\Form\FormBuilder->processForm('node_page_edit_form', Array, Object) (Line: 314)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 74)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

EDIT:

It looks like this was caused by a menu link being a child of a menu item that has an external link, and pathauto/token breaking on that.

Is there a way to improve the experience, like a form error instead of "website encountered an error" white screen?

# Answer
> 3 votes
Ok, based on the stacktrace, this happens somewhere during token replacements.

Your token for the alias is:

> Drupal\Core\Utility\Token-\>replace('\[node:menu-link:parent:url:relative\]/\[node:title\]', Array, Array, Object) (Line: 193)

But it looks like that fails because your menu parent seems to be a non-routed URL, could be a external URL or it could be a known issue with drush and Drupal 8.2 that I fixed in https://github.com/drush-ops/drush/pull/2393. Make sure you are on the most recent drush version and do a `drush cr`.

Doesn't look related to paragraphs to me at all. I suggest you open an issue in token.module with that backtrace. It should catch that or check it before trying to get the relative path. That would then still result in a wrong alias, it is likely not the actual problem (unless you really have an external link there but then your pathauto configuration can't work).

---
Tags: 8, uri, navigation
---


# Question
Title: Saving and retrieving EntityAutocomplete value
I'm building a block plugin that allows users to specify a menu to appear in a block plugin. I'm taking advantage of the EntityAutocomplete form element.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/class/EntityAutocomplete/8.2.x

Here is how the form is built.

```
public function blockForm($form, FormStateInterface $form_state) {
    $form['menu'] = [
        '#type'          => 'entity_autocomplete',
        '#target_type'   => 'menu',
        '#default_value' => $this->configuration['menu'],
    ];
    return $form;
}

```

It's able to display the form element just fine. And it allows users to select menus as well. I then save the item on submit like this.

```
public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['menu'] = $form_state->getValue('menu');
}

```

However after saving it and opening it again I receive this error

> InvalidArgumentException: The #default\_value property has to be an entity object or an array of entity object

How do I successfully save or retrieve the menu? Do I need to put something like $this-\>configuration\['menu'\]\['value'\]?

Update: When I perform

```
die(print_r($this->configuration['menu']));

```

It just prints the machine name of the menu I selected. So maybe the issue is that the default value it's being supplied is just a string instead of the actual entity? But if so how would I get the entity from the machine name?

Update 2: I tried using

```
$menu = Entity::load($this->configuration['menu']);
die(print_r($menu));

```

But that didn't produce anything.

# Answer
I was able to resolve the issue by loading the entity first like so

```
$menu = \Drupal::entityTypeManager()->getStorage('menu')->load($this->configuration['menu']);
    $form['menu'] = [
    '#type'          => 'entity_autocomplete',
    '#target_type'   => 'menu',
    '#default_value' => $menu,
];

```

The value of $this-\>configuration\['menu'\] was only the machine name, not the actual entity. So the entity had to be loaded and stored in a variable first.
> 4 votes

---
Tags: forms, 8
---


title: Struggling with view results

text:
# Question
Title: Struggling with view results
I'm struggling with view results. This is the first time I've ever posted on one of these! I set up a view to filter responses from a survey on a webform. The responses are supposed to show up if one required question is marked true. The other filters are exposed.

The problem is that the results do not show up correctly. Two of the results are included twice, and after a certain date, none of the results are included. Can anyone help? Thank you!

# Answer
> 1 votes
Set query option distinct so that results are included just once

and check your filter criteria, maybe you included some date condition.

---
Tags: views
---


# Question
Title: How to display/hide a field only if has a certain value?
I am working on an event content type. It contains a date field that lets users input the date in which their event will take place.
But sometimes the date of the event isn't known at the time the node is created. Users just need to create the event and discuss with other users (in the comments section) then decide when to organize it and add the date then.
So the date field has no default value and I created another boolean field that controls whether the date field is displayed or not using the conditional fields module.

The boolean field has two values, TRUE = « I know the date of my event ».
FALSE = « I will pick a date later »
The field is set to TRUE « I know the date of my event » by default.
If the user picks False « I don't know the date of my event yet », then the date field is hidden and no value is input.

The problems i'm facing are : When displaying the event as a node and when listing all the events in a view :

If the user knows and inputs the date of the event :
\- How to only display the date and hide the TRUE/I know the date of my event label/value of the boolean field

If the user chooses to pick a date later :
\- How to display a « Date to Be Determined » message and hide the empty date field.

If you have ideas or a better way to handle this, you're welcome

# Answer
> 1 votes
Hope youre feeling better! You should be able to achieve this by:

1. exclude the Date field from view.
2. in the Later Date field, under "rewrite results" check "Rewrite the output of this field. at the bottom of that fieldset expand Replacement patterns to see all the tokens available. You should see somethine like \[Date\] to indicate the content from the Date field. Enter that into your text.
3. In the "no results behavior" section, enter "Date to Be Determined" in the "No results text" box. check Count the number 0 as empty (so when the box isn't checked it will show your "Later" message) and check "Hide rewriting if empty"
4. Save view and refresh caches

---
Tags: 7, datetime
---


title: What does the AdvAgg bundler do?

text:
# Question
Title: What does the AdvAgg bundler do?
The description for the AdvAgg bundler says:

> If not checked, the bundler will not split up aggregates.

I know that aggregation is merging files together and I take that splitting isn't the opposite of *aggregation*. What is it, then?

# Answer
> 6 votes
The short answer is to take advantage of the browser cache. It can also be used to take advantage of the number of parallel connections that the browser can make.

Example: Front page has a.css and b.css; node 1 has a.css, b.css and c.css. If using one aggregate then the user going from the front page to node 1 would have to download all of the CSS again. By splitting up the aggregate in a smart manner the user will only need to download c.css

# Answer
> 1 votes
Aggregated bundles can be aggregated in groups. For example, let's say there was some CSS you wanted included in the head tag and other CSS that should be included towards the bottom of your page. In this case there might be two aggregate groups.

In AdvAgg I believe the use-case you really want to look at is for JS more so than CSS. In JS you may have a "site-wide" group and a "theme" group and...

You can also have AdvAgg break up the groups by filesize or number of files being aggregated. There are some old browsers (read \<= IE6) that have some issues with number of included CSS and number of CSS definitions in a single CSS file... these settings can be used to help with that.

Also, there are some HTTP2 improvements that make file aggregation less necessary for the typical use case (fewer TCP connection === better), but sometimes you would still want to aggregate in order to keep certain files together since they are functionally similar.

---
Tags: css-js-aggregation
---


# Question
Title: How can I build my own jquery ui theme and select it?
I started using the datepicker from jquery. I noticed that by default it uses the provided theme in /core/assets/vendor/jquery.ui/themes/base/theme.css and /core/assets/vendor/jquery.ui/themes/base/datepicker.css.

There seems to be only the base theme available.

How can I create my own theme and tell drupal to use my jquery ui theme?

Ideally I would like to be able to select the jquery ui theme from a custom Drupal theme. This way I would be able to change automatically the jquery ui theme from the Appearance menu by changing the theme and use the existing overriding system if I have a sub theme inheriting from that theme.

# Answer
Use `libraries-override` in mytheme.info.yml.

These are examples from **test\_theme.info.yml**:

```
libraries-override:
  # Replace an entire library.
  core/drupal.collapse: test_theme/collapse
  # Remove an entire library.
  core/drupal.progress: false
  # Replace particular library assets.
  classy/base:
    css:
      component:
        css/components/button.css: css/my-button.css
        css/components/collapse-processed.css: css/my-collapse-processed.css
        css/components/container-inline.css: /themes/my_theme/css/my-container-inline.css
        css/components/details.css: /themes/my_theme/css/my-details.css
  # Remove particular library assets.
  classy/dialog:
    css:
      component:
        css/components/dialog.css: false
  # It works for JS as well.
  core/jquery:
    js:
      assets/vendor/jquery/jquery.min.js: js/collapse.js
  # Use Drupal-relative paths.
  core/drupal.dropbutton:
    css:
      component:
        /core/themes/stable/css/core/dropbutton/dropbutton.css: /themes/my_theme/css/dropbutton.css
  # Use stream wrappers.
  core/drupal.vertical-tabs:
    css:
      component:
        /core/themes/stable/css/core/vertical-tabs.css: public://my_css/vertical-tabs.css
  # Use a protocol-relative URI.
  core/jquery.ui:
    css:
      component:
        assets/vendor/jquery.ui/themes/base/core.css: //my-server/my_theme/css/jquery_ui.css
  # Use an absolute URI.
  core/jquery.farbtastic:
    css:
      component:
        assets/vendor/farbtastic/farbtastic.css: http://example.com/my_theme/css/farbtastic.css

```

Reference: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme See subsection *Overriding and extending libraries*
> 2 votes

---
Tags: theming, 8
---


title: Cannot start session for anonymous user

text:
# Question
Title: Cannot start session for anonymous user
I'm trying to start a session for anonymous users (using Drupal 8.2.2), so I can use the private temp store, but the session does not persist. This is what happens with anon users:

```
// $session is the Drupal `session` service (Symfony Session component)
$session->start();
var_dump($session->isStarted()); // always FALSE
var_dump($session->getId()); // changes from request to request

```

With an authenticated user, `isStarted()` returns TRUE, and the session ID remains the same.

How can I start a session for anonymous users that will enable private temp store?

# Answer
It's not necessary to use a private temp store for anonymous user if you don't have a lot of data. And for anonymous it's not so easy to implement this.

To store data for anonymous users you can simply use the php $\_SESSION variable.

```
$_SESSION['my_module']['data'] = 'My Data';

```

Drupal will take care of starting and saving the session.

Edit:

OK, to make this official, you should use the request object. See https://www.drupal.org/node/2380327. But drupal core and contrib code still uses the $\_SESSION variable. This should be OK at least for D8.

In both cases you have not to handle the session yourself. Drupal will load the session if there is one present when it begins with the request. And drupal will start a new session and saves it at the end of the request, if there is newly added session data.
> 2 votes

---
Tags: 8, sessions
---


# Question
Title: How to set a taxonomy term programmatically for a node?
I created taxonomy terms and assigned it to a content type '**Article**' using term reference field. I created nodes by programmatically but how to set taxonomy terms for the nodes?

The taxonomy terms are created already. I want to set the taxonomy term for a node **programmatically**.

# Answer
Use this function to get ID from Termname

```
function _get_tid_from_term_name($term_name) {
  $vocabulary = 'tags';
  $arr_terms = taxonomy_get_term_by_name($term_name, $vocabulary);
  if (!empty($arr_terms)) {
    $arr_terms = array_values($arr_terms);
    $tid = $arr_terms[0]->tid;
  }
   else {
    $vobj = taxonomy_vocabulary_machine_name_load($vocabulary);
    $term = new stdClass();
    $term->name = $term_name;
    $term->vid = $vobj->vid;
    taxonomy_term_save($term);
    $tid = $term->tid;
  }
  return $tid;
}

```
> 18 votes

# Answer
When you creating a node programmatically, you can assign it to any term like this:

```
$node = new stdClass();
$node->type = 'YOUR_CONTENT_TYPE_NAME';
$node->title = 'title';

$node->language = LANGUAGE_NONE;
node_object_prepare($node);

//id of your taxonomy term
$tid = 1;

//add term to a node field
//field_yourfield_name - machine name of your term reference field

$node->field_yourfield_name[$node->language][0]['tid'] = $tid;
node_save($node);

```
> 16 votes

# Answer
You can use some entity metadata wrappers to achieve that, e.g.:

```
try {
  $w_node = entity_metadata_wrapper('node', $entity);
  $w_some_term = entity_metadata_wrapper('taxonomy_term', 1234);
  $w_node->field_term_ref = $w_some_term->tid->value();
  $w_node->save();
} catch (Exception $e) {
  drupal_set_message(t('Error for node: @title, message: @error.',
        array('@title' => $w_node->title->value(), '@error' => $e->getMessage())), 'error');
  watchdog_exception('foo', $e);
}

```
> 2 votes

# Answer
When adding terms, I found I needed to add $term-\>parent = array(0) otherwise the taxonomy\_term\_hierarchy table isn't updated properly, and the terms don't show in the admin list page for that vocabulary
> 1 votes

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


# Question
Title: How to make address1 field and zip code non required with Address Field module
I'm using Address Field module

I want to make it a required field but only the Country and City values. I want to leave the zip code and Address as optional. I don't find a way to configure it like this. Is it possible?

To provide more info, I am using Geocoder to fill a Geofield field. I want it to be able to geolocate with City and Country if only that are provided if also zip code and address are provided use them too.

EDIT: I forgot to mention that if I make the whole Address field non-required works as I want to, but I would like to make Country and City required, another way to look at the problem.

# Answer
I would use form\_alter to hook into the form, identify the form element and unset or make required FALSE

eg:

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

  if($form_id == 'xyz'){
   $form['zipcode']['#required'] = FALSE;
   $form['address']['#required'] = FALSE;
  }

}

```
> 1 votes

---
Tags: 7, location, entities
---


# Question
Title: How to access the fields in the comment reply page?
I'm using Drupal 7.

I show the form of comments in a page different from that of the nodes.

In this page, having for url mysite/comment/reply/..., I would like to modify the fields of the node which appear before the form of comments.

For example, the page looks like :

```
        Add a comment
-
        Title of the node
        Field 1 of the node (display)
        Field 2 of the node (hide)
-
        Comment form

```

I tried to create a specific page template : page--comment--reply, but I have no access to fields and cannot thus change their appearance.

Do you know how can it be done?

# Answer
I think comment.tpl.php is what you need

however you can also alter the display of comments in the display option on the content type.

look in "admin/structure/types/manage/CONTENT\_TYPE\_MACHINE\_NAME/comment/display"
> 0 votes

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


title: login state and a field condition

text:
# Question
Title: login state and a field condition
like to alter a template depending on a content type, let's say article and in-depth article if the user is logged in and if a boolean checkbox field is checked or not.

So how to alter these tree conditions programmatically for let's say the video\_embed\_filed?

I am new to Drupal 8 and Twig.

Thank you for your replies.

Thank you for your replies.

# Answer
1.content type specific template would be: node--type-article
2.{% if logged\_in %} will return boolean.
3.{% if (node.field\_video\_embed\_filed.value != NUll) %} or null can e replaced by your condition or you can use kint devel modue for better filtering like: {{ kint(node) }}
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Is it possible to declare option inside drupal_add_js?
I'm stuck on including an external JavaScript file on a custom page. The API service requires the HTML to be formatted as below

```
<script type="text/javascript" src="//platform.example.com/api.js">
api_key:   [key]
</script>

```

No idea if this can be done the Drupal way. I tried:

```
// load SDK
drupal_add_js('//platform.example.com/api.js', 'external');
drupal_add_js('api_key:   [key]', 'inline');

```

But without success. The API\_key declaration need to be done inside the first tag that links to the external JS. I know you can add extra parameters like documented on https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_js/7.x but this case is not described.

# Answer
> 2 votes
You can try something like

```
$external_js = array(
  '#markup' => '<script type="text/javascript" src="//platform.example.com/api.js">
    api_key:   [key]
  </script>',
);

drupal_add_html_head($external_js, 'my_module');

```

---
Tags: 7, javascript
---


title: Drush field-clone with specified label

text:
# Question
Title: Drush field-clone with specified label
The following command clones the field with the same label.

```
drush field-clone field_tags newtags

```

As you see, the cloned field has the same title **Tags**.

So how can I clone the existing field with desired label?

# Answer
> 0 votes
Based on the help for this command I'd say it is not possible:

```
$ drush help field-clone
Clone a field and all its instances.

Examples:
 field-clone tags labels                   Copy 'tags' field into a new field 'labels' field which has same
                                           instances.
 open `field-clone tags labels`            Clone field and then open field edit forms for refinement.

Arguments:
 source_field_name                         Name of field that will be cloned
 target_field_name                         Name of new, cloned field.

```

**Edit**: This GitHub issue can confirm it.

But you can always go to **Manage Fields**, edit the new field and change its name.

---
Tags: 7, entities, drush
---


# Question
Title: Add AJAX to form that was loaded through AJAX
I may be missing something really basic here but it has been bothering me for a couple of days now.

I have a page that basically contains a link which loads another page through AJAX. The page that is loaded is basically a simple node/add form for articles. The problem is that the form that is loaded does not contain any AJAX behavior (I even installed the AJAX example module and the simple ajax checkbox that it is adding does not work). I do not know if it relevant but the fieldsets in the node add form are not working either.

I did some research and I am suspecting that I need to do something on the AJAX callback that loads the form. I read about Drupal.attachBehaviors which I tried attaching to the element where I'm loading my form but it does not seem to be working.

I'd be happy to edit my question to add some code but I was wondering if I'm missing something really basic.

Edit (my current code):

PHP:

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

  $items['aforms/article'] = array(
    'page callback' => 'aforms_get_form',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'delivery callback' => 'aforms_ajax_callback',
  );

  return $items;
}

function aforms_get_form() {

  global $user;

  module_load_include('inc', 'node', 'node.pages');
  drupal_add_library('system', 'drupal.ajax');

  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => 'article',
    'language' => LANGUAGE_NONE,
  );

  $form = drupal_get_form('article_node_form', $node);

  return $form;

}

function aforms_ajax_callback($form) {

  print drupal_render($form);

  drupal_page_footer();

}

```

JS:

```
(function ($) {

Drupal.behaviors.aforms = {
    attach: function(context, settings) {
        $('body').on("click", "#load-me-up", function() {

            $('#target-container').load('/aforms/article', function() {
                console.log('Before attach behaviors executed');
                console.log(context);
                console.log(settings);
                Drupal.attachBehaviors();
                console.log('After attach behaviors executed');
                console.log('Drupal object:');
                console.log(Drupal);
            });

        });
    }
}

})(jQuery);

```

# Answer
> 1 votes
You need to provide `Drupal.attachBehaviors` with the context (what was added) and the `Drupal.settings`. You should also use context in your script, so the JS should be rewritten something like this (not tested)

```
(function ($) {

  Drupal.behaviors.aforms = {
    attach: function(context, settings) {
      $('body', context).on("click", "#load-me-up", function() {
        $('#target-container').load('/aforms/article', function() {
          Drupal.attachBehaviors($(this), settings);
        });
      });
    }
  }

})(jQuery);

```

You need to use context on the `$('body')` to avoid the handle to be attached multiple times. In the load callback you need to add `$('#target-container')` to `attachBehaviors`, but in this case `$(this)` should be the same thing.

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


# Question
Title: Programatically change user field (entity reference) in drupalgap with user_save()?
We are using DrupalGap to make an app. We have nodes (content type chargingstations) which we want our users to be able to "check" into by pressing a button. Until now I have created a button on the nodes page in DrupalGap which executes a function on an onClick event.

This function takes in a NID which is the node I want the user to check into. I then have a field on the user called "checked\_in\_chargingstation" which is an entity reference field.

In the DrupalGap documentation there is not much information on user\_update. It just says "...". But it seems like you can update a node by passing the NID. So I figured I could do the same for user? But it doesen't seem to work. I get a success alert, but I can't see any changes to the users.

My check in code. Drupal.user.uid gets the current users uid.

```
function check_in($nid){
  var $field_checked_in_chargingstation = {};
  $field_checked_in_chargingstation["und"] = {
    target_id: $nid,
  };

  var user = {
    uid: Drupal.user.uid,
    field_checked_in_chargingstation: $field_checked_in_chargingstation,
  }

  user_save(user, {
    success:function(result){
      console.log(result);
    }
  });
}

```

In the console I get:

Looking at the json I can see:

```
"field_checked_in_chargingstation": {
 "und": [
  {
   "target_id": "29088"
  }
 ]
},

```

But this is the wrong id. This is an old node which I have assigned before from Drupal and "edit" user. So it doesen't seem updated. Trying to drush cc all doesen't seem to work either.

If I try to edit the user from the app I only see null values for the entity reference field. One suggestion in the Drupalgap documentation is to make an entity reference view http://docs.drupalgap.org/7/Entities/Entity\_Reference which I also did.

Sorry if this is a bit long. And I'm not sure if I should post it here on Stack Exchange or as an issue on DrupalGap.

# Answer
> 2 votes
It depends largely on what Widget you have selected for your entity reference field on your Manage Display page. The easiest widget to work with is the Autocomplete widget, at which point you'd send up this JSON:

```
"field_checked_in_chargingstation": {
 "und": [
  {
   "target_id": "... (29088)"
  }
 ]
},

```

The Services module is coupled with the forms system in Drupal, so as you change the widget on a field, the JSON data you need to send to Drupal may change.

---
Tags: entities, javascript
---


title: Searching fields in Group module

text:
# Question
Title: Searching fields in Group module
I cannot figure out how I can be able to search the fields(set as a new content type) in the Group module.

For example, I created Groups(Group-Shop, Group-Salon, etc) under Group-Type-A with 3 fields containing:

* Name: J-Shop
* Type of Shop: Motor Shop
* Address: Chicago (uses geolocation)

After I added more data, I wanted to be able to search an item (Motor) and ALL related results should have shown up on the map (address of each items).

I've tried using a view with filter *group content*, but of course it would only search for related results (text) and clicking on the item/name would point me to the detailed info. I was looking to filtering/searching via Address/Geolocation of each group.

# Answer
I found an answer to my question. Its all in the view settings.

First, I changed the format from unsorted list of items/groups to Geolocation - CommonMap and modified its settings. This is to display all groups in a single map(A simple solution that I should have noticed at first).

Second, I added all fields needed to be displayed in a group in the map.

Lastly, I added desired filter(this is to search for a group).
> 1 votes

---
Tags: 8, entities, search, group
---


# Question
Title: How to add rows to a form table with AJAX Callback in Drupal 8
I try to implement a button to add rows to a form table. Each clic on the button should add a new line.

My problem is that my modifications in the AJAX Callback doesn't seem to modify the actual $form object :

At the first clic, row n°6 is added but without default values, wich is already a problem. The next clics have no effect, the $form parameter in the callback doesn't contain the 6th row.

What is the way to actually modify $form ?

Here is the build form :

```
public function buildForm(array $form, FormStateInterface $form_state, Array $profile = NULL) {

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

// table
$form['myTable'] = array(
'#type' => 'table',
'#header' => array(t('COL 1'), t('COL 2'), t('COL 3')),
'#prefix' => '<div id="my-table-wrapper">',
'#suffix' => '</div>',
);
// Build the table rows and columns.
for ($cpt = 0; $cpt <= 5; $cpt++) {
// Table row
$form['myTable'][$cpt] = $this->getTableLine($cpt);
}
$form['addRow'] = array(
    '#type' => 'button',
    '#value' => t('Add a row'),
    '#ajax' => array(
            'callback' =>  '::ajaxAddRow',
            'event' => 'click',
            'wrapper' => 'my-table-wrapper',
    ),
);

return $form;

}

```

Here the function called to fill the rows :

```
function getTableLine($key) {
    $line = array();

    $line['col_1'] = array(
            '#type' => 'textfield',
            '#default_value' => 'col 1 - row ' . $key,
    );
    $line['col_2'] = array(
            '#type' => 'textfield',
            '#default_value' => 'col 2 - row ' . $key,
    );
    $line['col_3'] = array(
            '#type' => 'textfield',
            '#default_value' => 'col 3 - row ' . $key,
    );
    return $line;
}

```

And the Ajax callback :

```
function ajaxAddRow($form, $form_state) {
    $cpt=0;
    for ($x = 0; $x <= 10 & $form['myTable'][$x]; $x++) {
        $cpt++;
    }

    // $cpt always return 6 - expected to increment
    // $form['myTable'][$cpt] is always empty

    $form['myTable'][$cpt] = $this->getTableLine($cpt);

    return $form['myTable'];

}

```

# Answer
> 2 votes
> **Details and Warnings**
>
> Changes to the form must only be made in the form builder function (ajax\_example\_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

Reference: https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7

It's for D7, but the concept how Ajax works has not changed:

> **The Big Idea**
>
> The big idea here is that:
>
> * Your form gets rebuilt when you manipulate a form element (e.g. select, submit etc.)
> * Your form builder function builds it a different way based on that input ($form\_state)
> * Your #ajax settings and your callback function arrange to deliver all or a part of the newly rebuilt form to replace or otherwise enhance some part of the page.

# Answer
> 0 votes
I managed this by detecting each click and setting a click counter in a hidden element of the form.

Everything is done in the buildForm, the callback function simply returns the form element to refresh.

```
public function buildForm(array $form, FormStateInterface $form_state, Array $profile = NULL) {

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

    // table
    $form['myTable'] = array(
        '#type' => 'table',
        '#header' => array(t('COL 1'), t('COL 2'), t('COL 3')),
        '#prefix' => '<div id="my-table-wrapper">',
        '#suffix' => '</div>',
    );
    // Build the table rows and columns.
    for ($cpt = 0; $cpt <= 5; $cpt++) {
        // Table row
        $form['myTable'][$cpt] = $this->getTableLine($cpt);
    }

    // Build the extra lines
    $triggeringElement = $form_state->getTriggeringElement();
    $clickCounter = 0;
    // if a click occurs
    if ($triggeringElement and $triggeringElement['#attributes']['id'] == 'add-row') {
        // click counter is incremented
        // $formstate and $form element are updated
        $clickCounter=$form_state->getValue('click_counter');
        $clickCounter++;
        $form_state->setValue('click_counter',$clickCounter);
        $form['click_counter'] = array('#type' => 'hidden', '#default_value' => 0, '#value' => $clickCounter);
    } else {
        $form['click_counter'] = array('#type' => 'hidden', '#default_value' => 0);
    }

    // Build the extra table rows and columns.
    for ($k=0 ; $k<$clickCounter ; $k++) {
        $form['myTable'][6+$k] = $this->getTableLine(6+$k);
    }

    $form['addRow'] = array(
            '#type' => 'button',
            '#value' => t('Add a row'),
            '#ajax' => array(
                    'callback' =>  '::ajaxAddRow',
                    'event' => 'click',
                    'wrapper' => 'my-table-wrapper',
            ),
            '#attributes' => array(
                    'id' =>  'add-row'
            ),
    );

    return $form;

}

```

---
Tags: forms, 8, ajax
---


# Question
Title: How to redirect search result page in drupal
Here, I am working in drupal Commons plugin. I already customized search form in that drupal header.Here i include modify search form in custom theme:

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['custom_search_types']['#attributes'] = array('style' => 'display:none'); // Set a default value for the textfield
    $form['search_block_form']['#attributes']['class'][] = 'form-control'; // Set a default value for the textfield
    $form['actions']['submit']['#value'] = 'OK!'; // Change the text on the submit button

    $form['actions']['submit'] = array('#type' => 'button','#value' => 'OK!');

    // Add extra attributes to the text box
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search') {this.value = '';}";
    // Prevent user from searching the default text
    $form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";
    $form['actions']['submit']['#attributes']['class'][] = 'input-group-addon';

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
  }
}

```

And i need to redirect search result page using that above search form.But I type content and hit enter it remain same page.How to redirect into search result page with custom form values.I just customized form submit in custom theme

```
function mytheme_search_box_form_submit($form, &$form_state) {
print_r($form);//No results
}

```

How to achieve it. kindly guide me..

# Answer
You can use the **redirect** attribute in form\_state as follows,

```
function mytheme_search_box_form_submit($form, &$form_state) {
   $form_state['#redirect'] = 'Your path to redirect';
}

```
> 1 votes

# Answer
Here's a complete example. First you add a custom form handler:

```
function yourmodule_form_alter(&$form, $form_state, $form_id) {

  switch ($form_id)  {

  case 'search_form':
    $form['#submit'][] = 'yourmodule_search_box_form_submit';
  break;

  }
}

```

Then you redirect. Here's an example adding the search terms to the URL:

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

   $search_terms = $form_state['input']['keys'];

   $form_state['redirect'] = 'some/path/'.check_url( $search_terms );

}

```

If it doesn't work, try adding `$form_state['rebuild'] = FALSE;` to the second function, and try toggling between `$form_state['redirect']` and `$form_state['#redirect']`
> 0 votes

---
Tags: theming, search, 7, views
---


# Question
Title: Drupal installed as composer package, Custom themes/modules folder
I want a folder structure similar to:

```
-web
--app
---themes
---modules
--core

```

In composer I can specify installer paths to put required modules in the /web/app/modules directory and install drupal core in the /web/core.

Can I get Drupal to look for themes and modules in the /web/app/themes and /web/apps/modules directories so I don't have to put anything custom inside the core directory (so Drupal core can be installed as a package and not stored in my git repo).

I've seen similar set ups with Wordpress allowing you to specify a 'CONTENT\_DIR' constant that means Wordpress will look for wp-content in a different directory. Is there a similar way for Drupal?

I found this on git which achieves something but it requires a custom script https://github.com/davidbarratt/drupal-structure

# Answer
Drupals extensions discovery looks only in some specific folders (see http://cgit.drupalcode.org/drupal/tree/modules/README.txt for more information).

But, you don't have to put your own modules inside of the core folder. You should use /modules instead.

The Drupals default directory is not ideal for a development workflow with composer in mind. Take a look at https://github.com/drupal-composer/drupal-project if you have not already.
> 1 votes

---
Tags: composer
---


# Question
Title: 8: How to specify multiple css media types in a libraries.yml file
Entering the list "screen, print" doesn't work:

```
base:
  version: VERSION
  css:
    theme:
      css/styles.css: { media: screen, print }

```

The resulting HTML should be:

```
<link rel="stylesheet" type="text/css" href="css/styles.css" media="screen,print" />

```

# Answer
```
css/styles.css: { media: "screen,print" }      # outputs media="screen,print" (WORKS!)
css/styles.css: { media: ['screen', 'print'] }  # outputs media="screen print"

```
> 2 votes

# Answer
if you are working with sass, you can also call other css files from your style.sass file, with a simple import:

```
// custom sass file for domo theme
@import "variables";
@import "front";
@import "formulario";

```

i had called many files from my library doing this:

```
global-styling:
  css:
    theme:
      css/style.css: {}

bootstrap-scripts:
  js:
    bootstrap/js/affix.js: {}
    bootstrap/js/alert.js: {}

```
> 0 votes

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


title: “&” displaying as “&”

text:
# Question
Title: “&” displaying as “&”
I'm Using File (Field) Paths

“&” displaying as “&” in the file name

i tried to solve it by change the the display of the field to plain text and use the token view mode but nothing change

Any help?

# Answer
You should always prevent special characters in filenames, this can lead to strange behavior. Specifically because certain characters can be part of a query string (`example.com/index.php?var1=value1&var2=value2`).

I recommend the Transliteration module (assuming Drupal 7) to remove these charaters form the filename. If that does not help (or if you are using Drupal 8), you might want to take another look at you upload configuration. There might be a token provided by File (Field) Paths that does provide you with a good encoded name.
> 0 votes

---
Tags: 7, files, tokens
---


# Question
Title: Render block programmatically in Drupal 8 returns 0
I create a block at `/admin/structure/block/block-content` and I want programmatically render it in our custom template files. What I did is

```
function hook_preprocess_page(&$vars) {

    $block = \Drupal\block_content\Entity\BlockContent::load(2);
    $vars['contact-us-info-block']= \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
    //kint( ($vars['contact-us-info-block']));
    //kint( drupal_render($vars['contact-us-info-block']));
}

```

and in page template file I try

```
<p>{{ contact-us-info-block }} </p>

```

but I only see a "0" in output.

**if I use**

```
$vars['contact-us-info-block'] = drupal_render($vars['contact-us-info-block']);

```

everything is Ok but I find out *drupal\_render* is deprecated in Drupal 8. Where is problem and **how can I render a block at page template programmatically?**

# Answer
> 1 votes
For display only your block in your templates with preprocess the best way is

```
$block = Block::load('my_block_id');
$variables['My_region'] = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($block);

```

And in your page.html.twig or node.html.twig or xxx.html.twig use your variable My\_region like this :

```
{% if page.My_region %}
    {{ page.My_region }}
{% endif %}

```

And in rendable array (custom module) by exemple into an controller custom in content():

```
public function content() {
    $block = Block::load('my_block_id');
    $block_content = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($block);

          return array(
            '#type' => 'container',
            '#attributes' => array(
            'class' => array("Myclass"),
          ),
           "element-content" => $block_content,
           '#weight' => 0,
  );
}

```

drupal\_render is not usefull drupal already assume the render in D8 and this is deprecated (https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal\_render/8)

it's a bit heavy, it is better to use the maximum area system and does not add load block from the preprocess. In the case of using a controller in your modules this seems a justified use.

# Answer
> 1 votes
Attentively see topic: https://drupaldeveloper.in/codelet/drupal8-set-block-region-programmatically

You add and display block correctly but have some mistakes in your code.

The first mistake when you load block:

```
$block = \Drupal\block_content\Entity\BlockContent::load(2);

```

Do you have block with id "2"? As I understand you have block with id "block\_content" and you need load this block.

After that you need add block to variables and you did, but make mistake in method getViewBuilder() you must set 'block', not 'block\_content'.

Also, you don't need to use drupal\_render. So the final correct code must be next:

```
function hook_preprocess_page(&$vars) {

    $block = \Drupal\block_content\Entity\BlockContent::load('block_content');
    $vars['contact-us-info-block']= \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
}

```

# Answer
> -1 votes
```
function hook_preprocess_page(&$vars) {
  $block = \Drupal\block_content\Entity\BlockContent::load(2);
  $blockview = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
  $vars['contact-us-info-block'] = render($blockview);
}

```

---
Tags: theming, 8
---


# Question
Title: How to make a form with latest nodes listing with checkboxes same as in 'admin/content' page?
I want to create a custom module for newsletter composer in drupal 7. To create a newsletter I need to show latest 100 nodes in a form with a checkbox and a dropdown (Select box) to select the section user wants to show the node.

In admin/content page same node listing appears. I need a select box within that check box, So need two elements in a row.

Please suggest me how to achieve the node listing table in a form with two fields and a node title in a row.

# Answer
First off all you can see how this realize in **/admin/content** page. The file ***/modules/node/node.admin.inc*** has a `function node_admin_nodes()` This function returns form which contain list of nodes. The file has clear description and you can read and copy-paste code from this function to your module with necessary modifications.
> 0 votes

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


# Question
Title: How can I programmatically alter a view query?
I need to be able to pass a date+time argument to a view. When I add a date field as a contextual argument, the query is only passing this in Y-m-d format. I need to include the time so that I can get a list of events that are happening at a certain time.

I think I should be able to use views\_query\_alter to change the -\>where condition, but I'm not sure where to go from there. If I do this:

```
function mymodule_views_query_alter($view, $query) {
  if ($view->current_display == 'mydisplay') {
    dsm($query->where[0]['conditions'][0]['field']);
    $query->where[0]['conditions'][0]['field'] = ???
  }
}

```

This is the output from the dsm:

```
DATE_FORMAT(node__field_session_date.field_session_date_value, '%Y-%m-%d') = :node__field_session_date_field_session_date_value

```

How do I change that %Y-%m-%d to include the time in the correct format?

# Answer
> 1 votes
I would approach this from a different angle. You can create a new Datetime argument type (a views plugin) and then add an association for your desired field to your new argument. This means we aren't modifying a query in an unpredictable way, and you can see in configuration that the argument is different. You can set this up to use any date format you wish, but keep in mind that time zones may affect the values.

First, we'll create the new argument type. We're extending the existing base Date argument and only changing the date format. The @ViewsArgument value will need to match the argument id value in the field assignment later on.

mymodule/src/Plugin/views/argument/FullDatetime.php:

```
<?php

namespace Drupal\mymodule\Plugin\views\argument;

use Drupal\datetime\Plugin\views\argument\Date;

/**
 * Argument handler for a full datetime (CCYYMMDD-HHMM).
 *
 * @ViewsArgument("mymodule_full_datetime")
 */
class FullDatetime extends Date {

  /**
   * {@inheritdoc}
   */
  protected $argFormat = 'Ymd-Hi';

}

```

And now we'll create a new argument assignment for the Session Date field.

mymodule/mymodule.module:

```
/**
 * Implements hook_views_data_alter().
 *
 * @param array $data
 */
function mymodule_views_data_alter(array &$data) {
  $data['node__field_session_date']['field_session_date_full_datetime'] = array(
    'argument' => array(
      'field' => 'field_session_date_value',
      'field_name' => 'field_session_date',
      'id' => 'mymodule_full_datetime',
      'table' => 'node__field_session_date',
    ),
    'group' => $this->t('Content'),
    'help' => $this->t('Date in the form of %format.', array('%format' => 'YYYYMMDD-HHMM')),
    'title' => $this->t('@field', array('@field' => 'Session Date (Full Datetime)')),
    'title short' => $this->t('@field (@format)', array('@field' => 'Session Date', '@format' => 'YYYYMMDD-HHMM')),
  );
}

```

Now you just need to add the `Session Date (Full Datetime)` argument to your view in place of the argument you were trying to override.

---
Tags: views, 8
---


# Question
Title: What is the best way to add a confirmation tooltip to the remove button of a managed_file field?
## Another Update

I'm trying to implement the solution found here: Intercept click event on a button, ask for confirmation, then proceed, but the remove button still submits normally. I know my JS is targeting the correct element, because I can change other attributes on it like the background color.

Here's my form:

```
function form_experiments_01() {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'form_experiments') . '/js/form_experiments.js',
  );

  $form['managed_files'] = array(
    '#type' => 'fieldset',
    '#title' => t('Managed Files'),
  );

  $num_docs = 3;
  for ($i = 1; $i <= $num_docs; $i++) {
    $form['managed_files'][$i] = array(
      '#type' => 'managed_file',
      '#title' => 'Managed File ' . $i,
    );
  }

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

  return $form;
}

```

Here's my javascript:

```
(function ($) {
  Drupal.behaviors.managedFileAutoUpload = {
    attach: function(context, settings) {
      $('.form-item input.form-submit[value=Upload]', context).hide();
      $('.form-item input.form-file', context).change(function() {
        $parent = $(this).closest('.form-item');

        //setTimeout to allow for validation
        //would prefer an event, but there isn't one
        setTimeout(function() {
          if(!$('.error', $parent).length) {
            $('input.form-submit[value=Upload]', $parent).mousedown();
          }
        }, 100);
      });
    }
  };

  Drupal.behaviors.managedFileConfirmRemove = {
    attach: function(context, settings) {
      var myButton = $('.form-item input.form-submit[value=Remove]', context);

      if (myButton.length > 0) {
        var myClick = null;

        //get a list of jQuery handlers bound to the click event
        var jQueryHandlers = myButton.data('events').click;

        console.log(jQueryHandlers);

        //grab the first jquery function bound to this event
        $.each(jQueryHandlers,function(i,f) {
          myClick = f.handler;
          return false;
        });

        //unbind the original
        myButton.unbind('click');

        //bind the modified one
        myButton.click(function(){
          if(window.confirm("Are You Sure?")){
            myClick();
          } else {
            return false;
          }
        });
      }
    }
  }
})(jQuery);

```

## Update

After some more research I found this question. This is what I was trying to ask but didn't know how to word.

Intercept click event on a button, ask for confirmation, then proceed

I'll implement this solution and post a resolution once I've got it working.

## Description

I would like to add a confirmation tooltip when the "remove" button is clicked on my `managed_file` field.

I would like to do something similar to this:

What is the best way to do that?

## Possible Solution?

So far, I'm thinking I could probably use javascript to hide the remove button and instead display my own button. Then when my button is clicked, I can trigger a popup that contains a second custom button to cancel and the remove button that I originally hid.

I'm worried that this solution is a bit messy. Is there a more elegant way to do this? Can I get a similar behavior without hiding the original remove button?

## Similar Questions

I'm not sure if these apply to my use-case since I'm working with a `managed_file` field. So far, I've been unable to implement similar solutions without the default behavior of the remove button interfering.

## Resources

# Answer
Use this code to delay submit and display popup before submitting.

```
$("form").submit( function () {
   //display tooltip something
   return true;
 }

```

Something like this:

```
$('.form-item input.form-submit[value=Remove]').submit {
  if (window.confirm("Are You Sure?")) {
    myClick();
  } else {
    return false;
  }
}

```
> 0 votes

---
Tags: entities, javascript, ajax
---


# Question
Title: 7 allow cross-origin framing CORS module
I am embedding content in my article that are from the same domain. when I am opening my url with HTTP the embedded HTTPS content won't open and when I am opening my url with HTTPS the embedded HTTP content won't open. Same thing happen when i try to open content with localhost. I am getting this error in Firefox and Chrome:

```
Load denied by X-Frame-Options: http://mywebsite.com/embed/clips/sandy does not permit cross-origin framing.

```

OR

```
 Refused to display 'https://mywebsite.com/embed/clips/sandy' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

```

I installed the CORS module but it does not seems to help. In Domains (/admin/config/services/cors) I added:

```
*|<mirror>,https://mywebsite.com
*|<mirror>,https://mediamatters.org

```

without success. Any insight is apreciated.

# Answer
https and http -- even if the host is the same -- are considered different domains.

The way you can deal with that when your site can be viewed with both https and http, is instead of referencing files https:// or http:// just use // It will defer to the protocol that you are on.

The only time this would cause problems would be if a certain resource only got served up under secure or insecure. But this does not sound like it would be a problem for you in this instance.

EDIT: In order to change existing content, which it sounds like doing by hand is impossible. You could try a module like https://www.drupal.org/project/scanner -- being careful to backup, test, and make sure you are only looking at the correct URLs (you don't want to change the urls where changing the protocol would be).

One other possible way to make it work is to just make your path references root relative -- strip out http://yourdomain.com \- and just leave /your/path/to/file

The other thing to do is just cherry pick the content that people are looking at most.
> 2 votes

---
Tags: 7
---


# Question
Title: How to sort a view on a numeric field treating it as boolean?
Slightly unusual case. I've got a Drupal Commerce store making hand-made goods, where the client wants sold stock to be visible in product list views marked as sold out, always at the end of every list, so that people who've browsed all the available stock without finding what they want can get ideas based on products that have been made before and could put in a request for something like a previously sold product to be made.

So, **I want a sort that takes the commerce stock field, which is a fairly ordinary numeric field, and sorts on it, but treating all numbers greater than or equal to 1 as 1.**

The conversion is easy, the sorting algorithm would be easy to code, and I'm sure this could be done with a very small custom module hook somewhere in the Views sort process - I'm just not sure which of the many Views hooks would be the appropriate position in the views sorting process to modify the field value like this. Also, there might be a better way. I'd prefer not to create a duplicate boolean field then sort on that, as it might end up out of sync.

How can I sort on a numeric field like it was a boolean field like this?

# Answer
You would have to probably sort against the stock level field **and then also** sort against the boolean. That is native in Views.

So, Add the sort to sort by the Boolean field and sort with DESC so that the out-of-stock items fall to the bottom.

And then under it add your default sort (stock level) as normal.

Edit: Reading into this again and rereading your question... I will expand the above. there are two ways to do this.

1. is above - with the addition of a boolean field which would have to get flipped if your stock levels drop to zero. you could use rules to make that happen and populate the field based on the condition as part of your checkout ruleset.
2. You might also be able to accomplish this with views aggregation to group and modify that sort.
> 1 votes

# Answer
Not the most elegant solution, but it still works...

Have you view in two displays: main (anything) and zeros (attachment)

* In the main, set a filter with your field and a condition "greater than" 0. (Not greater than or equal to zero")
* In the zeros display, set your field and a condition "equal to" 0.

If you want the rows with the field = zero first, add the attachment before; if last, add the attachment after.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Count content views show in number with icon
I have enabled Count content views in Statistics.

The bottom of article show "3 reads".

I checked the code, the code is `<span>3 reads</span>`

Because the number and word is together, I can't change word "reads" to an "eye" icon.

How do I show the number with icon.

Below is the effect I want

# Answer
> 2 votes
Assuming you're using D7, you can implement `hook_node_view()` in your custom module and override statistics count text as per your requirement. Check example below:

```
/**
 * Implements hook_node_view().
 */
function [YOUR_MODULE_NAME]_node_view($node, $view_mode) {
  if ($view_mode != 'rss') {
    if (user_access('view post access counter')) {
      $statistics = statistics_get($node->nid);
      if ($statistics) {
        // Alter text as per your requirement below.
        $links['statistics_counter']['title'] = format_plural($statistics['totalcount'], '<i class="icon"></i>1 read', '<i class="icon"></i>@count reads');
        $node->content['links']['statistics'] = array(
          '#theme' => 'links__node__statistics',
          '#links' => $links,
          '#attributes' => array('class' => array('links', 'inline')),
        );
      }
    }
  }
}

```

---
Tags: nodes
---


title: Views Block Question

text:
# Question
Title: Views Block Question
I created a view that is a block. I then wanted to create another block for that view but with different criteria. When creating the second block, it was identical to the first block created and when I lets say change the fields, the first original block gets changed as well. So it seems anything I do to the new block changes the first block as well.

What is the purpose of being able to create a second block but it is the exact same as the first? I think the only difference it can have is a display name? Can anyone explain this to me or give me an example of the purpose of this functionality?

# Answer
Change the "For" setting in the header whenever changing almost anything.

If you want the setting to change on **both displays** choose "All displays":

If you want the setting to change on **only one display** choose "This block (override)"
> 5 votes

# Answer
You can create another view block within same view with a difference to change the fields on both views can be done. The process is when you create a fields on second view just use override this display for each field on second view and if you want to delete some fields from second view that is being carried over from first view is by opening the popup by clicking the field in second view and select override this display option with in popupp and then remove. If you escape the step of overriding the field in second view and remove the field from second view the field will also be removed from first also.
> 3 votes

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


# Question
Title: How to use owl carousel in custom module?
I am trying to call Owl Carousel from a custom module, but despite the short description of how to do that on https://www.drupal.org/node/2412689, can't figure out.

I could use Views, but then I need to call either list of nodes or node fields, but in this case, I have several items which need to be rotated in a variable. I could put them into array if the implementation requires it.

So basically my question is:

Given a list of items in a variable (or array) how can I rotate them using the Owl Carousel module?

# Answer
> 0 votes
Assuming you've an array, you can print the array items one by one in wrapper `<div>` tag, and apply Own Carousel to wrapper `<div>` tag (check `owl-demo` class in example below). To do this in Drupal, you can process your array in your module to create HTML, and apply JS using `drupal_add_js()`. To print HTML you can either create a custom block and show on page or create custom page.

**Implementing in Drupal with custom module:**

```
function _owl_carousel_demo() {
  $array = array('User 1', 'User 2', 'User 3', 'User 4', 'User 5', 'User 6', 'User 7');
  $output = '<div id="owl-demo" class="owl-carousel">';
  foreach ($array as $value) {
    $output .= '<div class="item"><h1>' . $value . '</h1></div>';
  }
  $output .= '</div>';
  $output .= '<div class="customNavigation">
    <a class="btn prev">Previous</a>
    <a class="btn next">Next</a>
    <a class="btn play">Autoplay</a>
    <a class="btn stop">Stop</a>
  </div></div>';

  drupal_add_css('http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.css', 'external');
  drupal_add_js('http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.js', 'external');
  drupal_add_js('jQuery(document).ready(function() {
      var owl = jQuery("#owl-demo");
      owl.owlCarousel({
        items : 4,
      });
    });', 'inline');

  return $output;
}

```

**Below example shows complete HTML:**

```
<html>
  <head>
    <link href="http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.css" rel="stylesheet">
    <link href="http://owlgraphic.com/owlcarousel/owl-carousel/owl.theme.css" rel="stylesheet">
  </head>
  <body>
    <?php $array = array('User 1', 'User 2', 'User 3', 'User 4', 'User 5', 'User 6', 'User 7'); ?>
    <div id="demo">
      <div class="container">
        <div class="row">
          <div class="span12">
            <div id="owl-demo" class="owl-carousel">
              <?php foreach ($array as $value) : ?>
                <div class="item"><h1><?php echo $value; ?></h1></div>
              <?php endforeach; ?>
            </div>
            <div class="customNavigation">
              <a class="btn prev">Previous</a>
              <a class="btn next">Next</a>
              <a class="btn play">Autoplay</a>
              <a class="btn stop">Stop</a>
            </div>
          </div>
        </div>
      </div>

    </div>

    <script src="http://owlgraphic.com/owlcarousel/assets/js/jquery-1.9.1.min.js"></script>
    <script src="http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.js"></script>
    <script>
    $(document).ready(function() {
      var owl = $("#owl-demo");
      owl.owlCarousel({
        items : 4, //10 items above 1000px browser width
      });
      // Custom Navigation Events
      $(".next").click(function(){
        owl.trigger('owl.next');
      })
      $(".prev").click(function(){
        owl.trigger('owl.prev');
      })
      $(".play").click(function(){
        owl.trigger('owl.play',1000);
      })
      $(".stop").click(function(){
        owl.trigger('owl.stop');
      })
    });
    </script>
  </body>
</html>

```

---
Tags: 7, javascript
---


# Question
Title: Split an array of ids and save it as individual rows in table
I managed to get all ids from a table using query in drupal. I got the array of ids. I'm struggling to insert all the ids in another table as individual rows. As Im new to the drupal concepts,its very difficult for me to figure it out. Any help is appreciable.:)

# Answer
You can use db\_insert in your module OR drupal\_write\_record

E.g: drupal 7 code

```

 //Assuming your array is like
 /*
   $ids = array(1,2,3,4,5,6,....);
 */

  // Traversing ids by using foreach loop
  foreach($ids_array as $key=>$value){
       $custom_table_data = array(
            'id'=>$value,// id value
            'column1'=>'..'
        );

       // INSERT INTO {table_name} (field_1, field_2, ...) VALUES ('ABC', '123', ....)
        $nid = db_insert('table_name') // Table name no longer needs {}
        ->fields($custom_table_data)
        ->execute();

        // OR using drupal_write_record...
        drupal_write_record('table_name', $custom_table_data);
  }

```
> 1 votes

---
Tags: 7
---


# Question
Title: How to get Fragment value from url in Drupal 8?
I need to get the Fragment value from url like: admin/config/system/meta\_custom?query=test#abc=xyz in Drupal 8.

Need value of abc - ideally using Drupal's API, rather than doing my own Url Parsing.

# Answer
You could use it like this:

$path = \Drupal::request()-\>getpathInfo(); $arg = explode('/',$path);

It gives:

Array ( \[0\] =\> \[1\] =\> node \[2\] =\> add \[3\] =\> application )
> 1 votes

---
Tags: uri
---