# Question
Title: Main Menu link to all newsletters and another for Articles
I am very new and not a developer. I would like to create two main menu links for newsletter content type (simplenews) and the core articles type. I want the behavior to be the same as blog.

I assumed that simplenews would add the link when installed but it did not. I have been searching the net for hours, I cannot find a solution.

Thank you in advance for your help.

# Answer
> 0 votes
How much I understand go to structure \> menu \> main menu and click "***add link***" for Drupal 7 and structure \> menu \> main navigation for Drupal 8    and for this, you need to create two views one is for newsletter content type and second is for article content type. You can make the view by going to structure \> views \> ***add new view*** for both Drupal 7 and 8. The view type must be page not block.

***All the pictures are for Drupal 8. If you need more assistance please let me know.***

---
Tags: navigation
---


title: Show content dependent on user choice

text:
# Question
Title: Show content dependent on user choice
For a car selling website, there is need that the user choose his car and depending on his choice, another list should appear with the available models.

I search to do this on a conditional system, but also a list with hidden submenus would be acceptable.

# Answer
If you want when user select a Car and then according to select car another select list showed with that car model I can suggest you use simple hierarchical select module ( I know it hasn't stable version yet),

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.
>
> This module has been inspired by Hierarchical select but is much simpler (hence the name ;) ).

Also conditional fields is very good module to achieve field show and hide based on another field but it is not suitable for your case.
> 4 votes

# Answer
It is working with simple hiarchical select module. Because of the long complex lists difficult to handle in Taxonomy, I also work with the Taxonomy Manager module : https://drupal.org/project/taxonomy\_manager It show some errors, but it works fine and once the work is done, you can uninstall it for your production website.
> 0 votes

# Answer
I found the original title of your question quite misleading. Conditional fields is actually the wrong direction. Go for Views. Check out the docs.

---

### Views

Let's say you have a content type "Car" and it has a lot of fields. Now first create a View to list all "Car" nodes, sort them by whatever you want, display them however you want.

Next add *filters* to your view (docs) and *expose* them to your visitors (docs). These filters can filter by any field of your "Car" node type. Maybe a brand filter, and a max. speed filter, and a color filter. As soon as these filters get applied (with an "Apply" button or via auto-submit) the view then only lists all "Cars" that matches the given criteria.
> 0 votes

---
Tags: 8
---


# Question
Title: Multiple form buttons with AJAX, how to update form state storage data?
I have a form built with the Form API that has multiple `button` form elements. I don't want any of these to submit the form normally, I want them to utilize `#ajax` and callbacks to update the display. I feel like I run into this on every so often and can't quite remember how to make it work.

When the form first loads, I want half of the buttons to be `disabled`. When one of the buttons is clicked, I want to be able to detect this in `buildForm` so I can set form defaults and remove the `disable` property so other buttons can now be used.

I thought I could set storage in the callback and read it back the next time the form is built:

```
// Relevant bit of the form...
$form['#prefix'] = '<div id="my-form-wrapper">';
$form['#suffix'] = '</div>';

$form['actions']['#type'] = 'actions';

$form['actions']['update'] = [
  '#type' => 'button',
  '#value' => $this->t('Start Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'update'],
    'method' => 'replace',
  ]
];

$form['actions']['reset'] = [
  '#type' => 'button',
  '#value' => $this->t('Reset Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'reset'],
    'method' => 'replace',
  ],
  '#disabled' => TRUE,
];

// The AJAX callback
public function update(array &$form, FormStateInterface $form_state) {
  $form_state->set('flag_1', TRUE);
  $form_state->set('flag_2', "Started!");
  $form_state->setRebuild();
}

```

The callback fires, and I see `$form_state` storage get updated with those arbitrary values, but when the form is rebuilt, I do not see them in `$form_state` anymore.

I looked at a few other similar form API AJAX questions, but did not have any luck getting unstuck.

Note: I do not want to have to juggle this with jQuery. I want to be able to update form data behind the scenes and rebuild the form appropriately with the relevant data.

# Answer
> 2 votes
Please try this, as **@4k4** suggested you have to first build a normal form and ajaxify by using #ajax, and from the method defined inside #ajax you can return a $form and any fields inside the wrapper.

```
// Relevant bit of the form...
$form['#prefix'] = '<div id="my-form-wrapper">';
$form['#suffix'] = '</div>';

$form['actions']['#type'] = 'actions';

$form['actions']['update'] = [
  '#type' => 'button',
  '#value' => $this->t('Start Form'),
  '#submit' => ['::setAjaxSubmit'],
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'update'],
    'method' => 'replace',
  ]
];

$form['actions']['reset'] = [
  '#type' => 'button',
  '#value' => $this->t('Reset Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'reset'],
    'method' => 'replace',
  ],
  '#disabled' => TRUE,
];

// The AJAX callback
public function update($form, FormStateInterface $form_state) {
//return $form or part inside the ajax wrapper
return $form;
}

// The submit callback
public function setAjaxSubmit($form, FormStateInterface $form_state) {
  $form_state->set('flag_1', TRUE);
  $form_state->set('flag_2', "Started!");
  $form_state->setRebuild();
}

```

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


# Question
Title: How to display node details and call function in *.html.twig
I work in D8, I create a custom module first\_module. By modules create a url and display all nodes by \*.html.twig file.

Write code in controller.php

```
public function contentthree() {

  $connection = Database::getConnection();

  $query = $connection->select('node', 'n');
  $query->fields('n', ['nid', 'type']);

  $groups = $query->execute()->fetchAll();

  foreach ($groups as $group) {
    $events[] = [$group->nid, $group->type];
  }

  return [
    '#theme'  => 'first_module_display',
    '#events' => $events,
  ];
}

```

In \*.module

```
function first_module_theme($existing, $type, $theme, $path) {

  return [
    'first_module_display' => [
      'variables' => ['events' => NULL],
      'template'  => 'first-module-list',
    ],
  ];
}

function _get_node_details() {

  $output = 'Welcome D8';

  $output .= 'Node Details';

  return $output;
}

```

and create templates first-module-list.html.twig and display data

```
{%for key, data in events %}

{%for key1, data1 in data %}

   {{ data1 }}

{% endfor %}

{% endfor %}

```

work fine and showing data correct. But, my question is how to call `function _get_node_details()` and how to render node details in `first-module-list.html.twig` files?

# Answer
I think I would have implemented this feature differently. Let me just answer the specific question, and then I will tell you an alternative approach.

### Custom 'functions' in Twig

The easiest thing for you could be to Implement a twig macro.

However, macros could be limiting. To have all the PHP power you can create a *twig extension function*

If you are in a rush and are into bad practices, then there is the twig tweak *php filter*, so that you can do this:

```
<div class="bad-practice">
     {{ 'return _get_node_details();'|php }}
</div>

```

### Alternative implementation using Drupal views

* Create a Drupal View, with a Block Display.
* Place the new Block, using the Block Layout.
* If you need to do a heavy alteration use a hook\_views\_data\_alter().
> 2 votes

---
Tags: 8, nodes
---


title: Auto add shipping line item

text:
# Question
Title: Auto add shipping line item
I want to auto add flat rate shipping cost to any order and display it in the shopping cart summary.

I am using Commerce Shipping and Commerce Flat Rate modules. I can't know how to implement it using rules.

I found this post but it didn't help me.

what I need is to automatically add $10 on every order for shipping, I will disable the Shipping Service Panel.

# Answer
> 1 votes
You can do this with Rules. Here is an example:

```
{
    "rules_auto_add_shipping_service" : {
      "LABEL" : "Auto-add shipping service",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "REQUIRES" : [ "rules", "commerce_order", "commerce_shipping", "entity" ],
      "ON" : { "commerce_order_update" : [] },
      "IF" : [
        { "data_is" : { "data" : [ "commerce-order:type" ], "value" : "commerce_order" } },
        { "commerce_order_contains_product" : {
            "commerce_order" : [ "commerce_order" ],
            "product_id" : "YOUR-SKU-HERE",
            "operator" : "\u003E=",
            "value" : "1"
          }
        }
      ],
      "DO" : [
        { "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
        { "commerce_shipping_method_collect_rates" : {
            "shipping_method_name" : "flat_rate",
            "commerce_order" : [ "commerce_order" ]
          }
        },
        { "commerce_shipping_rate_apply" : {
            "commerce_order" : [ "commerce_order" ],
            "shipping_service_name" : [ "" ]
          }
        }
      ]
    }
}

```

Just change the SKU or the other conditions to suit your needs.

# Answer
> 0 votes
You should be able to do this out of the box with FLAT RATE.

Just add your new FLAT RATE for $10 (yoursite.com/admin/commerce/config/shipping then click ADD NEW FLAT RATE) and it will show up in the shipping pane already selected when checking out. It will also create a new line item on the cart summary for SHIPPING.

This will add a $10 flat rate shipping method to every order \- if this is not what you are looking for please clarify, hope this helps.

---
Tags: commerce, rules
---


# Question
Title: Why do both Text- and Data comparison seem to not work in my Rules conditions?
I’m using Drupal 7.56, the Rules module 7.x-2.11, and CiviCRM 4.6.31.

I've been using the *Text comparison* and *Data comparison* conditions.

Using the *Text comparison* condition, the condition is always met, so the action is always executed, despite the value of the data.

Why does this condition always evaluate to `TRUE`, for all the possible values, even when the text of the data is different to the matching text?

This is the log entry.

> The condition text\_matches evaluated to TRUE.

This is the export of the rule.

```
{ "rules_create_a_drupal_account_for_a_civicrm_contact" : {
    "LABEL" : "Create a Drupal account for a CiviCRM contact",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules", "devel" ],
    "ON" : { "civicrm_membership_create" : [] },
    "IF" : [
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ] } },
      { "AND" : [
          { "NOT data_is_empty" : { "data" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ] } },
          { "AND" : [
              { "text_matches" : {
                  "text" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ],
                  "match" : "Parent"
                }
              }
            ]
          }
        ]
      }
    ],
    "DO" : [
      { "devel_debug" : { "value" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ] } },
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ],
            "is_active" : "1",
            "notify" : "0",
            "signin" : "0",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      },
      { "user_add_role" : { "account" : [ "civicrm-user" ], "roles" : { "value" : { "5" : "5" } } } }
    ]
  }
}

```

Using the *Data comparison* condition, the condition is never met and the action is never executed, despite the data to compare.

Why does this condition always evaluate to `FALSE`, for all the data, even when it is the same to the value to compare?

This is the log entry.

> The condition data\_is evaluated to FALSE.

This is the export of the rule.

```
{ "rules_create_a_drupal_user_account2" : {
    "LABEL" : "Create a Drupal User Account2",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules" ],
    "ON" : { "civicrm_membership_create" : [] },
    "IF" : [
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ] } },
      { "AND" : [] },
      { "data_is" : {
          "data" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ],
          "value" : "Parent"
        }
      }
    ],
    "DO" : [
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ],
            "is_active" : "1",
            "notify" : "0",
            "signin" : "0",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      }
    ]
  }
}

```

Any clue about what might be happening?

# Answer
I am not sure it is your ***only*** problem, but for sure you are not correctly using the AND constructs in your rule. It is one of the typical mistakes many Rules users make, but if you want to model a condition like ***A AND B***, then first you must have a line with AND, and that should be followed with A and then also folowed by B. Something like so:

```
AND
  A
  B

```

For way more details, refer to my answer to Combining AND and OR in Rules.

So start with fixing this, and then verify if your issue is solved or not.

As a sample, just import this minor variation of your last rule (note I slightly renamed the rule to not overwrite your existing one, and moved the AND construct to where it belongs):

```
{ "rules_create_a_drupal_user_by_pierre" : {
    "LABEL" : "Create a Drupal User By Pierre",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules" ],
    "ON" : { "civicrm_membership_create" : [] },
    "IF" : [
      { "AND" : [] },
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ] } },
      { "data_is" : {
          "data" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ],
          "value" : "Parent"
        }
      }
    ],
    "DO" : [
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ],
            "is_active" : "1",
            "notify" : "0",
            "signin" : "0",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      }
    ]
  }
}

```

If the above still doesn't solve your issue, then I suggest you do some extra Rules debugging as explained in my answer to "How can I display the value of a variable inside a condition?".

**Update**:

The above (related tot the AND-construct) is for sure "a" reason why it doesn't work. However, yet another issue you may have to correct, is related to what you wrote in a comment below this answer, i.e. this part of it:

> ... The value of the variable is the expected, but I'm not sure if I'm accessing in the right way to the variable, as it's an array: ... (Array, 1 element) 0 (String, 6 characters) Parent

If what you're trying to compare is an array (a "list of values"), then you should NOT (repeat: NOT) use something like a "Data Comparison", because that's like trying to compare an array with a single value (which doesn't make sense). To get your rule to work like you want it to work, you should use the Rules Condition ***List contains item***. For an example Rule (in Rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Show and require field if birthday (date field) is less than 18 years old
I have a field that should be **visible** and **required** if the user selects a date that would make them less than 18 years old. If they are over 18, the field should be hidden and not required. Right now, I am using this:

In **birthday.js**:

```
(function ($) {

$(document).ready(function() {
    $('#edit-field-minor-agreement').hide();
});

$(document).on('change', '#edit-field-dob-und-0-value-year, #edit-field-dob-und-0-value-month, #edit-field-dob-und-0-value-day', function() {
    var yyyy = $("#edit-field-dob-und-0-value-year").find(":selected").val();
    var m = $("#edit-field-dob-und-0-value-month").find(":selected").val();
    var d = $("#edit-field-dob-und-0-value-day").find(":selected").val();

    if ( $('#edit-field-dob-und-0-value-year').val() && $('#edit-field-dob-und-0-value-year').val() && $('#edit-field-dob-und-0-value-year').val() ){
        dateString = m + "/" + d + "/" + yyyy;
        var today = new Date();
        var birthDate = new Date(dateString);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        console.log("Birth date: " + dateString);
        console.log("Age: " + age);
    }

    if(age<18) {
        $('#edit-field-minor-agreement').show();
    } else {
        $('#edit-field-minor-agreement').hide();
    }

});
})(jQuery);

```

It is successfully setting the **visibility**, but I can't seem to figure out how to make it **required**. Any help is appreciated.

# Answer
> 1 votes
Here is a working solution. Huge thanks to @nikathone for assistance.

```
/**
 * Implements hook_form_FORM_ID_alter() for record_node_form.
 */
function mrpeanut_form_record_node_form_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['field_dob']) && !empty($form['field_minor_agreement'])) {
    $form['field_minor_agreement']['#prefix'] = '<div id="edit-field-minor-agreement-wrapper">';
    $form['field_minor_agreement']['#suffix'] = '</div>';
    $is_younger = TRUE;
    $values = !empty($form_state['values']) ? $form_state['values'] : array();
    $dob_date_combo_element = &$form['field_dob']['und'][0];
    $dob_date_combo_element['#ajax'] = [
      'callback' => 'mrpeanut_form_record_node_form_minor_agreement_callback',
      'wrapper' => 'edit-field-minor-agreement-wrapper',
      'effect' => 'fade',
    ];

    if (!empty($values['field_dob']['und'][0]['value'])) {
      $dob = new DateTime($values['field_dob']['und'][0]['value']);
      $now = new DateTime();
      $age = $now->diff($dob)->y;
      $is_younger = $age < 18;
    }

    $form['field_minor_agreement']['und']['#access'] = $is_younger;
    $form['field_minor_agreement']['und'][0]['#required'] = $is_younger;
  }
}

/**
 * Ajax callback for minor agreement.
 */
function mrpeanut_form_record_node_form_minor_agreement_callback($form, $form_state) {
  return $form['field_minor_agreement'];
}

```

---
Tags: 7, javascript
---


# Question
Title: What is the equivalent of domain_get_domain()?
I need the equivalent of `domain_get_domain()` in the Domain Access module for Drupal 8, but I can't find it.

I need to find the domain for the current request.

# Answer
> 3 votes
Finally worked out the following ...

```
$domainNegotiator = \Drupal::service('domain.negotiator');
$current = $domainNegotiator->negotiateActiveHostname();

```

There are other methods on the DomainNegotiator service that I thought should work, particularly `getActiveDomain()` and `getActiveId()`, but they didn't return the domain I was actually on like I thought they would.

It's still a bit confusing to me, but I made it work.

EDIT: @berramou 's answer below helped as well. Originally, I was looking for the Domain object (from the Domain Access module), but it turns out the host was enough to match a Domain reference on my entity.

# Answer
> 1 votes
In drupal 8 there is `\Drupal::request()` to get request info.

For Example if your url something like `https://example.com`

If you want only the domain name `example.com`

```
$domain = \Drupal::request()->getHost();

```

if you want the domain name with schema `http or https` `https://example.com` use this:

```
  $domain_with_schema = \Drupal::request()->getSchemeAndHttpHost();

```

---
Tags: 8, domain-access
---


# Question
Title: CSV Article Migration giving random errors
I've been working on a personal test site for a while and wanted to set up another one for someone else. This just involves running a migration to import all the articles from a CSV file. It's worked in the past but on the most recent attempts I keep getting errors.

I'm using the following modules:

* Migrate Plus
* Migrate Source CSV
* Migrate Tools

The error is not very specific. It just says failed migration. Below is the output of the migration `drush migrate-import article_import --debug`.

```
Using the Drush script found at /Applications/DevDesktop/tools/vendor/drush/drush/drush.launcher using proc_open
Loading drushrc "/Applications/DevDesktop/tools/vendor/drush/drush/drushrc.php" into "drush" scope. [0.01 sec, 2.95 MB]                                                                                [bootstrap]
Cache HIT cid: 8.1.17-commandfiles-0-d62e1df8f3ac5c588065a4c35f5fb135 [0.02 sec, 2.99 MB]                                                                                [debug]
Bootstrap to phase 0. [0.17 sec, 8.08 MB]                                                                                [bootstrap]
Bootstrap to phase 1. [0.17 sec, 8.08 MB]                                                                                [bootstrap]
Drush bootstrap phase : bootstrap_drupal_root() [0.18 sec, 8.57 MB]                                                                                [bootstrap]
Initialized Drupal 8.6.1 root directory at /Users/Noah/Sites/devdesktop/drupal-8.6.1 [0.19 sec, 8.58 MB]                                                                                [bootstrap]
Find command files for phase 1 (max=1) [0.19 sec, 7.08 MB]                                                                                [debug]
Cache HIT cid: 8.1.17-commandfiles-1-3124f7209a887277b55472999b93bdc2 [0.19 sec, 7.08 MB]                                                                                [debug]
Cache HIT cid: 8.1.17-annotationfiles-1-d7b3bf1ac55fb9d52f6b1a9cf998e002 [0.19 sec, 7.16 MB]                                                                                [debug]
Bootstrap to phase 5. [0.25 sec, 8.72 MB]                                                                                [bootstrap]
Drush bootstrap phase : bootstrap_drupal_site() [0.27 sec, 9.36 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [0.27 sec, 9.36 MB]                                                                                [bootstrap]
Find command files for phase 2 (max=5) [0.28 sec, 7.79 MB]                                                                                [debug]
Drush bootstrap phase : bootstrap_drupal_configuration() [0.28 sec, 7.79 MB]                                                                                [bootstrap]
Create from request [0.28 sec, 7.8 MB]                                                                                [debug]
add service modifier [0.28 sec, 7.95 MB]                                                                                [debug]
Find command files for phase 3 (max=5) [0.28 sec, 7.95 MB]                                                                                [debug]
sql-query: SELECT 1; [0.29 sec, 8.09 MB]                                                                                [notice]
Executing: mysql --defaults-extra-file=/private/tmp/drush_BFAC4P --database=drupal_8_6_1 --host=127.0.0.1 --port=33067 --silent  < /private/tmp/drush_e9fdFh
  1
sql-query: SHOW TABLES; [0.32 sec, 8.09 MB]                                                                                [notice]
Executing: mysql --defaults-extra-file=/private/tmp/drush_YSobxS --database=drupal_8_6_1 --host=127.0.0.1 --port=33067 --silent  < /private/tmp/drush_xf1Y3m
  batch
  block_content
  block_content__body
  block_content_field_data
  block_content_field_revision
  block_content_revision
  block_content_revision__body
  cache_bootstrap
  cache_config
  cache_container
  cache_data
  cache_default
  cache_discovery
  cache_discovery_migration
  cache_dynamic_page_cache
  cache_entity
  cache_menu
  cache_migrate
  cache_page
  cache_render
  cache_toolbar
  cachetags
  comment
  comment__comment_body
  comment_entity_statistics
  comment_field_data
  config
  config_snapshot
  file_managed
  file_usage
  history
  key_value
  key_value_expire
  menu_link_content
  menu_link_content_data
  menu_tree
  migrate_map_article_import
  migrate_message_article_import
  node
  node__body
  node__field_author
  node__field_date
  node__field_publication
  node_access
  node_field_data
  node_field_revision
  node_revision
  node_revision__body
  node_revision__field_author
  node_revision__field_date
  node_revision__field_publication
  queue
  router
  search_dataset
  search_index
  search_total
  semaphore
  sequences
  sessions
  shortcut
  shortcut_field_data
  shortcut_set_users
  taxonomy_index
  taxonomy_term__parent
  taxonomy_term_data
  taxonomy_term_field_data
  url_alias
  user__roles
  user__user_picture
  users
  users_data
  users_field_data
  watchdog
Drush bootstrap phase : bootstrap_drupal_database() [0.34 sec, 8.1 MB]                                                                                [bootstrap]
Successfully connected to the Drupal database. [0.34 sec, 8.1 MB]                                                                                [bootstrap]
Find command files for phase 4 (max=5) [0.34 sec, 8.1 MB]                                                                                [debug]
Drush bootstrap phase : bootstrap_drupal_full() [0.34 sec, 8.1 MB]                                                                                [bootstrap]
About to bootstrap the Drupal 8 Kernel. [0.34 sec, 8.1 MB]                                                                                [debug]
Finished bootstraping the Drupal 8 Kernel. [0.44 sec, 13.76 MB]                                                                                [debug]
Cache HIT cid: 8.1.17-install_profile-66ecfeb9791a023150773849f1550c5d [0.44 sec, 13.85 MB]                                                                                [debug]
Find command files for phase 5 (max=5) [0.44 sec, 13.91 MB]                                                                                [debug]
Cache HIT cid: 8.1.17-install_profile-66ecfeb9791a023150773849f1550c5d [0.44 sec, 13.92 MB]                                                                                [debug]
Cache HIT cid: 8.1.17-commandfiles-5-9bf3ecbb863ea82f59fb6b0b758fc109 [0.46 sec, 15.08 MB]                                                                                [debug]
Bootstrap to phase 6. [0.55 sec, 16.78 MB]                                                                                [bootstrap]
Drush bootstrap phase : bootstrap_drupal_login() [0.55 sec, 16.78 MB]                                                                                [bootstrap]
Find command files for phase 6 (max=6) [0.6 sec, 18.59 MB]                                                                                [debug]
Found command: migrate-import (commandfile=migrate_tools) [0.6 sec, 18.59 MB]                                                                                [bootstrap]
Calling hook drush_migrate_tools_migrate_import [0.71 sec, 20.45 MB]                                                                                [debug]
Calling Drupal\migrate_tools\MigrateExecutable::import() [0.72 sec, 21.26 MB]                                                                                [debug]
HERE --> Processed 116 items (0 created, 0 updated, 116 failed, 0 ignored) - done with 'article_import' [1.04 sec, 22.67 MB]                                                                                [status]
--> article_import Migration - 116 failed. [1.04 sec, 22.7 MB]                                                                                [error]
Returned from hook drush_migrate_tools_migrate_import [1.04 sec, 22.7 MB]                                                                                [debug]
Command dispatch complete [1.04 sec, 22.64 MB]

```

Below is my migration config:

```
langcode: en
status: true
dependencies: {  }
id: article_import
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: null
label: 'Import articles'
source:
  plugin: csv
  path: Path/To/articles.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    -
      id: 'Unique Id'
    -
      title: Title
    -
      date: Date
    -
      publication: Publication
    -
      body: 'Article body'
process:
  title: title
  field_author: author
  field_date:
    plugin: format_date
    from_format: m/d/Y
    to_format: Y-m-d
    source: date
  field_publication: publication
  body/format:
    plugin: default_value
    default_value: full_html
  body/value: body
  type:
    plugin: default_value
    default_value: article
destination:
  plugin: 'entity:node'
migration_dependencies: null

```

I'm using Acquia Dev Desktop, in case that makes a difference.

# Answer
You already use the module Migrate Tools. So you can use UI to check status and logs when you migrate. You need to visit url **admin/structure/migrate** to view list of migration and go to specific group to show status and logs.

Or you can check in your database, each migration have two tables to log status and message when migrate. One is **migrate\_map\_MIGRATION\_ID** and one is **migrate\_message\_MIGRATION\_ID**

In some case log message can write to table database. So you need debug to know why that row failed with tips `drush mim MIGRATION_ID --idlist=KEY_ROW_FAILED`. **Note: you need to know use xdebug.**
> 0 votes

---
Tags: 8, drush, importing-exporting
---


# Question
Title: date_default_timezone_get() returns the wrong timezone
I have several Drupal 7 sites using the same installation in the same server. Two of those sites are returning "Europe/London" when running `date_default_timezone_get()`. This timezone is different from the one returned by `drupal_get_user_timezone()` or `variable_get('date_default_timezone')`, which (correctly) return "America/Denver". For the rest of the sites the returned timezone is the same for all three functions.

The fact that I get a different timezone with the php function is creating issues for those two sites; for example, token replacements of date field are returning London time, not the site timezone's time.

What may be causing this discrepancy? Is there any way to correct that? I tried including the line `date.timezone = "America/Denver"` in `php.ini` without success.

I'm running php5.6 on Apache 2.4.36

# Answer
I figured out what was going on. I am using the module `print` with the external library `mPDF` (version 6.0). `mPDF.php` was changing my default timezone to "Europe/London" in line 80 (this bug has been reported in this version of mPDF). Apparently this line was running after `drupal_session_initialize()` in `session.inc`, which sets the default timezone for the session to match the site's selected timezone.

What's strange is that mPDF was only affecting 2 of my sites. Apparently the session initialization in the other sites was running after the mPDF command? I commented out those lines and all the timezones now match.
> 0 votes

---
Tags: 7
---


title: Remove seconds in time picker

text:
# Question
Title: Remove seconds in time picker
How do I remove or hide seconds in the Drupal 8 time picker?

# Answer
> 2 votes
The widgets for timestamps, datetime, and daterange fields is the HTML5 input elements. For time, the format for these has to be 'H:i:s', which includes the seconds. The form element also defaults to using the HTML5 inputs, too, in custom uses.

For fields, you would need to form alter the widget to change the 'date\_time\_element' key 'text' fields and update the '#date\_time\_format' key to the format you want. Then, you may need to update the submitted value to set the seconds to 00, since I believe they will default to the current value of the seconds.

For form elements, just use a 'text' element for '#date\_time\_element' and pick a format that you want.

# Answer
> 6 votes
I removed the seconds from the daterange widget by setting the step attribute in hook\_field\_widget\_WIDGET\_TYPE\_form\_alter() to 60 (seconds)

```
function my_module_field_widget_time_range_form_alter(&$element, FormStateInterface $form_state, $context) {
  $element['value']['#attributes']['step'] = 60;
  $element['end_value']['#attributes']['step'] = 60;
}

```

# Answer
> 4 votes
I accomplished this by doing what is recommended in this article.

If your module is `glue.module`, do this:

```
/**
 * Implements hook_element_info_alter().
 */
function glue_element_info_alter(array &$types) {
  $types['datetime']['#process'][] = 'glue_datetime_set_format';
}

/**
 * Element process callback for datetime fields.
 */
function glue_datetime_set_format($element) {
  // Remove seconds in browsers that support HTML5 type=date.
  $element['time']['#attributes']['step'] = 60;
  return $element;
}

```

# Answer
> 1 votes
For form fields set the step attribute to 0.

```
function THEME_preprocess_input(&$variables) {
  if ($variables['theme_hook_original'] == 'input__date' && $variables['attributes']['type'] == 'time') {
        $variables['attributes']['step'] = 0;
    }
}

```

---
Tags: 8, datetime
---


# Question
Title: How to do user relations, and User editing only their content?
Doing Drupal 8.6 is hard (I come from Laravel and Wordpress world).

I manage to do by myself OAuth token authentication with Vue, but I stopped on User relations and content-type. I know that where is programmer there is a way, but I just want to see what you do things then choose best option.

How can I, for example, create a friends system? With normal table structure is like this:

```
+----+--------+-----------+---------+
| id | sender | recipient |  status |
+----+--------+-----------+---------+
| 24 |   11   |    25     | [0,1,2] |
+----+--------+-----------+---------+

```

Is there built way in Drupal 8.6 to do it or should I get plugin? Or just do content-type Friendships with thse fields?

And when I allow user to create a Portfolio, the right way will be to create Content-Type Portfolio with Gallery field, and just give access to peoples to add nodes? How I can give User access to only edit or delete their own content?

# Answer
You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Some basics about he Group module to be aware of:

* Make sure you enable `gnode`, a submodule of the Group module.
* For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
* Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

With the appropriate permissions configured, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user. Refer to "How to create collections of content that can be accessed by users with various access levels?" for more info about all this.

**Resources**
> 1 votes

# Answer
Drupal projects are built like Lego bricks, you add modules/features that you need from contributed modules. There aren't many projects out there that only use core Drupal modules.

To take advantage of the most praised and sought after features of Drupal it's best to use the solution tailored for it.

Sometimes you might need a custom solution where you create your own module and define database schema, but usually, you just let ready-made solutions take care of most things because they are usually fully integrated with translation, testing, other modules you might want to use...

It would be best if you could describe the features you're after and let Drupalers suggest "the Drupal way" of doing things. Although keep in mind that direct questions about "which module should I use" are not allowed here.

## Drupal permissions | Edit own

Drupal Permissions system already offers a lot of control based on user Roles. Take a look there, and if it's not enough most other cases are covered with Content Access.

## Friends

A lot of cases where users mark other users in some way is done with Flag. You create the "Friend" flag and allow some Roles to use it. Then your users can mark other users as their friends. Lots of information about the flagging is recordered, and it's well integrated with Views so you can create your custom lists of Flags, for example list a person's friends on their profile, show latest "friendships" on the site etc.
> 0 votes

---
Tags: 8, nodes, users
---


title: Could a controller return binary data?

text:
# Question
Title: Could a controller return binary data?
This is my javascript request:

```
var XHR = new XMLHttpRequest();
XHR.responseType = 'blob';
XHR.addEventListener('readystatechange', function() {
    if (XHR.readyState == 4) {
        if (XHR.status == 200) {
            var blob = new Blob([XHR.response], {type: "application/mp3"});
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = 'Myfile.mp3';
            a.click();
            window.URL.revokeObjectURL(url);
        } else {
            document.getElementById(regidrs).innerHTML = "Error: " + XHR.responseText;
        }
    }
});

var FD  = new FormData();
FD.append('uuid', uuid);
XHR.open('POST', '/fetch');
XHR.send(FD);

```

This is my module routing:

my\_module/my\_module.routing.yml

```
my_module.content:
  path: '/fetch'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

```

And my controller:

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\drupal_set_message;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Defines HelloController class.
 */
class MyController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   *   Return markup array.
   */
  public function content() {
     ...
        $response= file_get_contents(....);
        $file = file_save_data($response, "public://myaudiofile.mp3", FILE_EXISTS_REPLACE);
     ...
     return [
      '#type' => 'markup',
      '#markup' => $response,
    ];
  }

}

```

But file\_get\_contents returns a mp3 file, and I need to pass this mp3 to the javascript httpresponse in order to donwload it. Saving $response to a file, I have checked the file is ok.

How can I do it?

# Answer
> 6 votes
With the `BinaryFileResponse` class, you can return the content of a file in the response. The `FileDownloadController` class is an example of controller returning the content of a file. It's the controller for /system/files/{scheme}, /system/files/{filepath}, and /system/temporary.
See its `FileDownloadController::download()` method.

```
public function download(Request $request, $scheme = 'private') {
  $target = $request->query
    ->get('file');

  // Merge remaining path arguments into relative file path.
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {

    // Let other modules provide headers and controls access to the file.
    $headers = $this
      ->moduleHandler()
      ->invokeAll('file_download', [
      $uri,
    ]);
    foreach ($headers as $result) {
      if ($result == -1) {
        throw new AccessDeniedHttpException();
      }
    }
    if (count($headers)) {

      // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
      // sets response as not cacheable if the Cache-Control header is not
      // already modified. We pass in FALSE for non-private schemes for the
      // $public parameter to make sure we don't change the headers.
      return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
    }
    throw new AccessDeniedHttpException();
  }
  throw new NotFoundHttpException();
}

```

The `ExportForm` class is another example of how to return a file, even if it's a form class. What changes is how the response is used, but how the `BinaryFileResponse` class is used is still relevant for a controller.
The relevant code is the following one, in `ExportForm::submitForm()`.

```
$response = new BinaryFileResponse($uri);
$response->setContentDisposition('attachment', $filename);

```

# Answer
> 0 votes
You are 99% there, just return a redirect to the file:

```
class MyController extends ControllerBase {

  public function content() {
     ...
        $response = file_get_contents(....);
        $file = file_save_data($mp3, "public://myaudiofile.mp3", FILE_EXISTS_REPLACE);
     ...
    return new RedirectResponse( file_create_url('public://myaudiofile.mp3'));

  }

}

```

---
Tags: 8
---


# Question
Title: How to use views filter on an entity property
I used hook\_entity\_property\_info\_alter to add two properties to an existing entity \[crm\_core\_contact\]. I find that I can see these two new properties in the "Fields" section of views, and that my views will display the values of those properties, but I cannot see these new properties in either the Sort or the Filter section of Views? Any ideas on documentation that might tell me what is going on?

Here is the code for one of the properties:

```
$properties = &$info['crm_core_contact']['properties'];
$properties['notes'] = array(
                'setter callback' => 'entity_property_verbatim_set',
                'setter_permission' => 'Administer wcgopindividualinfo content',
                'label' => 'NotesText',
                'type' => 'text',
                'schema field' => 'notes',
                'getter callback' => 'entity_property_verbatim_get',
                'entity views field' => TRUE,
                'getter_permission' => 'Administer wcgopindividualinfo content',
                );
```

Although the Trellon documentation does not say this, I'm wondering if I need to add a hook\_views\_data\_alter function to specify the filter and sort handlers for the properties that I added.

# Answer
I have now done some experimentation and find that yes, what I needed to do was use hook\_views\_data\_alter to tell views how to handle the properties I had added above. Here is the code inside my hook\_views\_data\_alter function:

```
$data['crm_core_contact']['notes'] = array(
            'title' => t('Notes'),
            'help' => t('The notes for the contact'),
         // Information for displaying the notes field
                'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
  ),

    // Information for accepting a note as a filter
        'filter' => array(
        'handler' => 'views_handler_filter_string',
  ),
    // Information for sorting on a note.
        'sort' => array(
        'handler' => 'views_handler_sort',
  ),
);

```
> 0 votes

---
Tags: views, entities
---


# Question
Title: How to reset form values when Ajax submits?
I develop a module which converts submit in the form to Ajax submit (e.g. `node/add/article`). After every submit, the node is successfully created, but all the values remain saved.

In the Ajax callback, I added a `return $form` to reload the form after submission, but all fields are empty, not filled with old values.

What shall I do?

# Answer
> 2 votes
You can try the code below

```
$response->addCommand(new InvokeCommand('#form-id','trigger',['reset']));

```

> The 'invoke' command will instruct the client to invoke the given jQuery method with the supplied arguments on the elements matched by the given selector. Intended for simple jQuery commands, such as attr(), addClass(), removeClass(), toggleClass(), etc.

This command is implemented by Drupal.AjaxCommands.prototype.invoke() defined in misc/ajax.js

Please see InvokeCommand

# Answer
> 0 votes
Using ajax submit option at form submit will stop reloading the page at the time of submission. Thus, to reload the values of field at submit will require

> $ajax\_response-\>addCommand(new HtmlCommand('#edit-field-name--description','your value'));

Sample code for this is -

```
    $form['custom_num'] = array(
'#type' => 'textfield',
'#description' => 'Enter a number',
'#size' => 80,
'#maxlength' => 250,
);
$form['calculate'] = array(
  '#type' => 'submit',
  '#value' => 'Check',
  '#ajax' => array(
    'callback' => '::submitForm',
    'event' => 'click',
    'effect' => 'fade',)
    );
public function submitForm(array &$form, FormStateInterface $form_state) {
  $ajax_response = new AjaxResponse();
  if ($form_state->getValue('custom_num') < 0) {
  $text = 'Negative Number';
  } else {
  $text = 'Positive Number';
  }
  $ajax_response->addCommand(new HtmlCommand('#edit-custom-num--description', $text));
  return $ajax_response;

```

}

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


# Question
Title: Programmatically Create an Array of User Objects and Print in Twig Template
**MYMODULE.module:**

```
function MYMODULE_preprocess_node(&$variables) {

    if ($variables['node']->bundle() == 'content_type') {

        $currentUserUID = \Drupal::currentUser()->id();
        $recipients = $variables['node']->get('field_user_reference')->getValue();
        $userList = array();

        foreach ($recipients as $recipient) {

            if ($recipient['target_id'] != $currentUserUID) {
                $userList[] = \Drupal\user\Entity\User::load($recipient['target_id']);
            }

        }

        if ($variables['node']->getOwnerId() != $currentUserUID) {
            $userList[] = \Drupal\user\Entity\User::load($variables['node']->getOwnerId());
        }

        $variables['userList'] = $userList;

    }

}

```

**FILENAME.twig.html:**

```
{{ userList | render }}

```

---

I've also tried working with:

```
$recipients = $variables['node']->get('field_user_reference')->view('compact');

```

and tried to filter the UID in the `if` statement inside the `foreach`.

---

My goal is to gather all users referenced from **field\_user\_reference**, and add the owner of the node, while filtering out the `currentUser()` into a single array. I then need to render that array in a twig template file as a user display mode. In this instance, `compact`.

I am not sure if my impasse lies in twig rendering, or better preprocessing.

How do you render a preprocessed user object in a twig template file?

---

Notes:

```
$recipients = $variables['node']->get('field_user_reference')->view('compact');

```

does render out the referenced users in the compact view mode, however I cannot seem to filter out the current user with something like `$recipient->uid[0]->target_id != $currentUserUID`.

# Answer
Before you can render a list of entities you have to build a render array:

```
$variables['userList'] = \Drupal::entityTypeManager()
  ->getViewBuilder('user')
  ->viewMultiple($userList, 'compact');

```

Now Twig is able to render the entities:

```
{{ userList }}

```

You don't need |render, because Twig renders arrays automatically.
> 2 votes

---
Tags: 8, theming, users, hooks
---


title: Private files and Nginx configuration

text:
# Question
Title: Private files and Nginx configuration
How to configure Drupal 7 to have private files folder. And also this configuration is secure within Nginx config.

# Answer
To set up a private files folder, navigate to: *Administration » Configuration » Media » File system*. Create a path from the *Unix* root for the "Private file system path" (e.g. `/var/files`) outside of the Drupal root.

Make sure that this folder is readable and writable by the web server user.

By having this folder *outside* of the Drupal root, it is secure. It cannot be compromised through the web server.
> 0 votes

---
Tags: 7
---


# Question
Title: Is it possible to search content by date in combined field filter views?
Is it possible to search content by date in combined field filter views?

I have created a view in which content title ,content body and content date field is showing of node news type,i have added combined field filter for searching node in views but its searching by body and title but not by date .

What is the solution for this issue?

# Answer
> 0 votes
Yes. Just make sure you have enabled the **Date Views** module (part of the **Date** project).

---
Tags: views
---


# Question
Title: Settings contains a dot which is not supported, but module gets enabled properly
I'm developing a search engine module for Drupal 8.

On a clean new Drupal website, I can install it from the admin GUI, but when I enable it I have the classical white screen (`The website encountered an error ...`).
Checking the `error.log` yields the following :

> Uncaught PHP Exception Drupal\Core\Config\ConfigValueException: "gref.settings key contains a dot which is not supported." at /var/www/html/core/lib/Drupal/Core/Config/ConfigBase.php line 211, referer: http://10.113.101.197/admin/modules

But, if I go back to the website, the module is installed properly, and no further issue is reported (even when uninstalling the module).

Here is my configuration :

```
- config
  - install
     - views.view.grefsearch.yml
     - search_api.server.grefserver.yml
     - search_api.index.grefindex.yml
     - gref.settings.yml
     - gref.schema.yml
     - facets.facet.grefother.yml
     - block.block.gref.yml

```

And here is gref.settings.yml

```
gref:
  page_title: 'Gref Search'
  source_text: 'Lorem ipsum dolor sit amet'

```

Any ideas why I have this error ?

# Answer
> 4 votes
Okay, classical scenario, 30 seconds after I open a bounty for the question, I find the answer myself ...

I was looking into the wrong file. I started the skeleton of my module by following this tutorial.

In the "Basic Structure" section of the tutorial, dots are used in keys for the `.schema.yml` file. It is actually forbidden to use that, but the tutorial said you could anyway.

```
/config/schema/loremipsum.schema.yml :

loremipsum.settings:
  type: config_object
  label: 'Lorem Ipsum settings'
  mapping:
    loremipsum:
      type: mapping
      mapping:
        page_title:
          type: text
          label: 'Lorem ipsum generator page title:'
        source_text:
          type: text
          label: 'Source text for lorem ipsum generation:'

```

I removed the dot at the key, and the problem disappeared.

---
Tags: 8, debugging, configuration
---


# Question
Title: Cannot access Administration > People page
I cannot access the People page. There is no error message. If I click on People in the menu bar, the Administration home page is shown.

The other Administration pages are accessible.

Similarly, if I click on Permissions for any module, I get the Administration home page; not the Administration \> People page.

The User module is enabled. I am logged-in as user #1.

I have checked the .htaccess file and do not see anything that would cause a problem.

I have tried disabling the handful of modules I have added.

What should I do next?

# Answer
I'm not sure 100% if my solution will solve your issue or not but give it a try

first set base url in settings.php

```
$base_url = 'http://baseurl.com/Drupal/htdocs';

```

then check if clean urls enabled from

```
/?q=admin/config/search/clean-urls

```

just in case try to clear Drupal cache from

```
/?q=admin/config/development/performance

```
> 1 votes

# Answer
I had the same error with PHP 7.1. Updated to the latest version of PHP and it worked!

Solution: upgrade your PHP.
> -1 votes

---
Tags: routes, users
---


# Question
Title: How to access node field content in a custom module?
I have a content type called districts and i have created the following fields

* district geojson(polygon values)
* harzards (list) - heavy rain, freezing rain, storm
* Alert level (list) - extreme, high, low

I am displaying in a view as a leaflet map. Now i would like to write a custom module that can get the field content of a nodes ie harzards and alert level and then pass them to a javascript file that will print specific colors to the districts in the view depending on the alert\_level.

What is the best way to get the field content (harzards and alert\_level) in to the custom module and then pass them to the javascript file? Or is there another way of achieving this. Thanks

# Answer
Assuming you mean Drupal 7, just off the top of my head, implement something like hook\_node\_view() and attach the Javascript via the #attached element. I am frequently silly in my hook options, so someone may have a better one to suggest.
> 0 votes

# Answer
Not sure if what you need, but you can always load the node (the object of your content type) with:

```
$district = node_load($district_nid);

```

And then you have access to it's fields:

```
$harzard = $district->field_harzard['und'][0]['value];

```

The last line may change, depending on your language configuration.

**OR** as suggested by @Juraj Nemec, use Drupal's function to access fields:

```
$harzard = field_get_items('node', $district, 'field_harzard');

```
> 0 votes

# Answer
Why not continue using the same View that builds the leaflet map? Doing so seems simplest and most 'standard' in the Drupal world.

Three options (at least) come to mind for setting your styling if you stick with Views:

1. use the Views Conditional module.
2. rewrite the field\_hazzard output to account for your conditions.
3. call the View in your custom module using views::getView.

Here's a step-by-step tutorial that accomplishes something similar using the 2nd option. It looks pretty good and broadly applicable: Conditional Formatting of Data In Drupal Views.
> 0 votes

---
Tags: views, javascript
---


# Question
Title: How to have custom ajax commands on element using InvokeCommand
How can i use custom ajax command using #ajax api , i have the following code working well

```
        $ajax_response = new AjaxResponse();
        $ajax_response->addCommand(new InvokeCommand('#edit-event-trigger', 'attr', array('disabled',true)));
        $ajax_response->addCommand(new InvokeCommand('#edit-event-trigger', 'removeAttr', array('placeholder')));
        $ajax_response->addCommand(new InvokeCommand('#edit-event-trigger', 'css',array("background-color", "")));
        //Return the AjaxResponse Object.
        return $ajax_response;

```

But suppose if i want to **`focus()`** or **`hide()`** the **`edit-event-trigger`** element , how could i do that ?

# Answer
> 5 votes
These are some examples you can try:

```
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'addClass', array('show')));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'removeClass', array('show')));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'attr', array('value', '123')));
$response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('.message', "Show this text"));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'css', array('background', '#dff0d8')));

```

Peace.

---
Tags: 8, ajax
---


# Question
Title: How to obtain the average of the number of a field according to the term of taxonomy?
I am using the default view Taxonomy term.

I added a "number" field to my article content type.

I would like to obtain the average of the fields of the nodes listed by term of taxonomy.

For example, I have two nodes, which have as fields numbers: 2 and 4, and whose term is common taxonomy: A.

I would like in the view of the term taxonomy A, get the average of the fields "number" of these nodes, namely 3.

I tried views aggregation, add two fields: a field of type "Content: title", with aggregation: Group together, and a field of type "AVG (Content: Note)", with aggregation: "Average".

But it does not work.

I tried to add different relationships, but without success.

Someone would know the right configuration of views to do that? Thank you

# Answer
> 0 votes
I'm not aware of a configuration that can do that out of the box on the Content type Views. But if it must be that exact Taxonomy Terms Views you can do it with the help of an additional module (check out Views Calc and Views Aggregator Plus).

But if you only want the result, to show the Average number on Term pages, then you can create a different View, of type Taxonomy term and display it as a Block on term pages. This type will work without additional modules.

1. Create `Term` Views type
2. Filter to your Vocabulary, filter Note field to be `Not empty`
3. Add the Taxonomy Name field, just to test, you'll see terms listed in separate Views rows
4. Add the Relationship to all content using the field `Content using Note`, (Relate each Content with a Note set to the term.) You can require this Relationship
5. DO NOT add any Sort criteria, sorting often messes up Aggregation
6. Add the Note Field, it will show separate Nodes' Note numbers in separate Views rows
7. Turn ON Aggregation
8. Edit the Note Field Aggregation and set it to `Average`, Group column `Value`

You should now again only see individual terms in rows, and the Note will show the average number calculated
9. Check the Note field Formatter, the Default might round the numbers not to show decimal places, Unformatted might show more
10. If this is all working the last thing to do is to add a Contextual filter to filter according to the term page you're viewing: Add the Contextual for the field relating to your relevant Taxonomy terms and configure it:
`When the filter value is NOT available`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from term page**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term ID**

Now you can enter a term ID into Preview field and you'll see what the block will display on that term's taxonomy page.

Place the block in a region, configure the block, limit the Visibility to term pages etc.

---
Tags: 8, views
---


# Question
Title: Add mini pager and infinite scroll to a view
I have a view where at first 1 item has to show. On click of 'load more' next item has to show and so on. For this i have installed 'infinite scroll module' in drupal 8. Now after showing four items, 'load more' has to change to ' show less' and hide all four items. I am not sure how to do this as infinite scroll module doesn't have this option.

Also, once there are four items are displayed, pagination with 'next' (on click showing next 4 items) has to appear.

I am not sure how to do this. Any help will be appreciated.

# Answer
You're description is a bit ambiguous because first you write

> Now after showing four items, 'load more' has to change to ' show less' and hide all four items

but then below you write

> Also, once there are four items are displayed, pagination with 'next' (on click showing next 4 items) has to appear.

Sounds to me like once there are 4 items displayed, you want to have a *show less* AND a *next* button to be displayed?

What's safe to say though, is that you can't get that show less button using views infinite scroll.

I'd probably try to add pagination using views infinite scroll that shows/loads additional 4 items when you click the load more button. The show less button you'll probably have to implement as custom JS wrapped inside a Drupal behavior .

You may also consider to override the JS behaviors of the views\_infinite\_scroll module to achieve the show more/show less functionality if it's not possible in a custom behavior because you depend on views\_infinite\_scroll's JS code to run first or so
> 2 votes

---
Tags: views, ajax, paging
---


# Question
Title: How to set the default theme programmatically
I've tried to set a theme as default theme in drupal 8 using the following code

```
> $config = \Drupal::configFactory()->getEditable('system.theme');
> $config->set('default', 'test_theme')->save();

```

On installing the module the code is not setting the theme as the one I've entered. The code is written in hook\_install().

# Answer
The current advice is to set this via config:

```
\Drupal::configFactory()
  ->getEditable('system.theme')
  ->set('default', $theme)
  ->save();

```

The previous method using `ThemeHandlerInterface::setDefault()` is now deprecated.

You might need to install it first too, I'm not sure. In case you do:

```
\Drupal::service('theme_installer')->install(['test_theme']);

```
> 9 votes

# Answer
I just want to contribute to this answer by adding that there's no need to worry about running both of these commands if the theme is already installed. It technically runs the theme\_installer service underneath and checks beforehand for installed themes.
> 1 votes

---
Tags: 8, theming, installation
---


title: How to edit <head> info

text:
# Question
Title: How to edit <head> info
In Drupal 6 the entire page data was stored in `page.tpl.php`. Now, with Drupal 7, only the content that appears in between `<body>` and `</body>`. So how do you edit the *HEAD info*? Is it still stored in a `.tpl.php` file? Where? If not, how do you do it?

# Answer
If the theme you use does not provide the file for the header, it means that Drupal is using the default one, which is now provided by a module called "system". The file is called html.tpl.php

Just copy this file into your theme, and edit it.
> 21 votes

# Answer
You need to copy default html.tpl.php from system module directory.

Or you can using function `drupal_add_html_head` to override or add new head tag.

```
// First, we must set up an array
$element = array(
  '#tag' => 'link', // The #tag is the html tag - <link />
  '#attributes' => array( // Set up an array of attributes inside the tag
    'href' => 'http://fonts.googleapis.com/css?family=Cardo&subset=latin',
    'rel' => 'stylesheet',
    'type' => 'text/css',
  ),
);
drupal_add_html_head($element, 'google_font_cardo');

```
> 11 votes

# Answer
If you want to change the head tag, you will need to use html.tpl.php
> 4 votes

# Answer
Copying html.tpl.php to your custom theme from the systems module will solve this issue. If you want to have the / tags in each of your custom .tpl files, you can just have only the following in your html.tpl.php file.

`<?php print $page; ?>`
> 0 votes

---
Tags: 7, theming
---


title: Geofield Map marker NODE ID

text:
# Question
Title: Geofield Map marker NODE ID
I have on Drupal 7 a Geofield Map Views that show a list of "Source" content on a Google Map.

I want to add on my marker on the map the information about the NID of the "Source" and I don't know how to do that.

The goal is to have my map and when I click on the marker, I get back the ID of the node and scroll down on the page to show the information about this Source.

Thanks in advance if anyone can help.

# Answer
> 0 votes
You can add a relationship, "Content" and make it available in fields.

If you can provide more details regarding your content type, I can provide a better answer.

---
Tags: 7, google-maps
---


# Question
Title: How to pass variables to overridden Twig template located in module?
I'd like to pass a variable to an overridden Twig template that is located in my custom module (not in a theme).

Following this answer and this answer, I wrote this code in *mymodule.module*:

```
function mymodule_preprocess_page(array &$variables) {
  $variables['hello'] = 'world';
}

function mymodule_theme_suggestions_node_add_list(array $variables) {
  $suggestions = [];
  $suggestions[] = 'node_add_list__' . 'custom';
  return $suggestions;
}

function mymodule_theme() {
  return [
    'node_add_list__custom' => [
      'base hook' => 'node_add_list',
    ],
  ];
}

```

Then, I have added in *mymodule/templates/node-add-list--custom.html.twig*:

```
myvar: {{ hello }}

```

However nothing appears after "myvar: " when I refresh the page. **I mention that I cleared the cache**.

Is there something specific to manage when we use `hook_preprocess_page()` with `hook_theme_suggestions_HOOK()`/`hook_theme()`?

# Answer
You need to `function MYMODULE_preprocess_node_add_list`.

```
function MYMODULE_preprocess_node_add_list(array &$variables) {
  $variables['hello'] = 'world';
}

```

This preprocess hook is actually called `HOOK_preprocess_HOOK`. See the last `HOOK` in its name? You need to target the `'base hook'` which is `node_add_list`. So preprocess that instead of the page.
> 3 votes

---
Tags: 8, theming, hooks
---


title: How to use between date query?

text:
# Question
Title: How to use between date query?
I have 2 fields in a node and I'm trying to get the expired nodes set in "Start Date" and "End Date" field.

I'm using db\_select to get the start and end date values.

How can I add a condition to check if the dates are in range?

Here's my current code:-

```
$query = db_select('node__field_end_date', 'ed');

$query->leftJoin('node__field_start_date', 'sd', 'sd.entity_id = ed.entity_id');

// Date values showing as a formatted date
$query->addField('ed', 'node__field_end_date', 'date_end');
$query->addField('sd', 'field_start_date_value', 'date_start');

```

# Answer
> 1 votes
The raw SQL would be something like this,

```
SELECT startDate, endDate
FROM YourTable
WHERE GETDATE() between startDate and endDate;

```

You might could do like this with db\_select

```
$query = db_select('node', 'n');
$query->condition(now(), array(node__field_start_date, node__field_end_date), 'BETWEEN');

```

I hope it helps

# Answer
> 1 votes
Something like this should do it:

```
db_select
  ...
  ->condition('date_field_1', $min_date, '>');
  ->condition('date_field_2', $max_date, '<=')

```

---
Tags: 8, database
---


# Question
Title: Load module config into Javascript from a different module
I have two Drupal modules.

One is a shared module that provides a JavaScript library. The second is a module that builds a form which uses that library.

Lets call them modlib and modform.

They've been written separately because the JS library needs to be used in multiple places, on various different forms, in different parts of the system.

This is working well. I can reference the JS code in modlib from within modform using `$form['#attached']['library']`.

However modlib also includes some configuration which needs to be loaded into `drupalSettings.modlib` for use within the JavaScript code. This isn't being loaded, and I'm unsure how to make it load from within modform.

Can anyone help? Thank you.

# Answer
Never mind, I solved it.

I've added a `preprocess_node` function to the module file of modlib, which looks a bit like this:

```
function mymodule_preprocess_node(&$variables)
{
    $apikey = \Drupal::configFactory()->getEditable('mymodule.apikeyconfig')->get('api_key');
    $variables['#attached']['drupalSettings']['mymodule']['pca'] = ['key' => $apikey];
}

```

So now the config value is being added to drupalSettings on every page load.

This is maybe not ideal (ideal would be only loaded when a relevant form is on the page), but it's good enough and means I don't have to have any logic in modform to load the config.
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: Bought Drupal Organization Membership But Cannot Create Listing
Recently, I bought DRUPAL ORGANZIATION MEMBERSHIP at $200 but now i am unable add my listing in drupal organzation list. And it also shows "not a confirmed user". Can someone help me with this ??

# Answer
> 2 votes
I understand that you've already created an organization page for Elsner Technologies Pvt. Ltd. on the Drupal marketplace, but that you want the listing to appear as a Drupal services provider.

If this is not yours, you may request its removal, or that ownership of the node is transferred to you so that you can edit it in the Drupal webmasters issue queue.

I've found this 4 year old application – which was denied.

The guidelines for being listed in Marketplace still apply, and you still do not qualify. Unfortunately, having a Drupal organization membership does *not* qualify for a listing. I suggest you re-read the comment given by *lizzjoy* as it contains good advice.

# Answer
> 1 votes
Being able to create an organization is not linked to buying the *Drupal Organization Membership* but to having the *confirmed* role. You need to request the *confirmed* role in the webmasters' queue, explaining that you need it to create the organization node. If you don't give that information, the webmasters will postpone the request until you don't post on drupal.org.

As for associating the organization membership with your organization, I cannot reply about that, but it's better to ask for support using the Drupal Association contact link. If you choose to contact them online, the *Contact the Drupal Association* green button will redirect you to https://www.drupal.org/contact. Select *Drupal Association membership* as category, enter the subject, the message, and click on *Send message*.

### Disclaimer

I am one of the Drupal.org webmasters and user administrators.

---
Tags: community-official-site
---


title: Registering Organisation in Drupal.org

text:
# Question
Title: Registering Organisation in Drupal.org
The Organization membership is of $200 and Individual membership cots $15. I wanted to confirm that if an organization account has been made. Do i have to pay $15/per person to add team members in my organizatiom's lisiting??

# Answer
If you take a organization membership, all the people in your organization will get an Organization member badge. You don't have to pay it separately.
> 1 votes

# Answer
> Do i have to pay $15/per person to add team members in my organizatiom's lisiting?

No.

The team members must add themselves. They do so by editing their personal profile. The right place is under the vertical tab "Work". They must add the organization in the "Organzation" field and tick "Current organization".

There is no charge for doing this.

You *need* to make your team members do this as one of the steps towards getting your organization listed as a Service provider in the market place.
> 0 votes

---
Tags: community-official-site
---


# Question
Title: Kint works in pre_process but not in Twig
On my site, I'm able to use print variables using kint in my pre-process functions.

However, when I try to do the same in twig, nothing happens. I do have debug mode turned on. Has anyone ever ran into this fact pattern? Any ideas?

**To clarify:**

* It does not work in any of my templates
* The specific template I'm using is for styling the output of a view, which is a page and has unformatted HTML as its type.

This is how I use kint  `kint()`

This is what I have seen on tutorials.

# Answer
> 1 votes
In php you use kint like this, `kint($variable)`, but in twig you use kint like this, `{{ kint(variable) }}`.

This is the only problem I can spot by looking at your question.

Hope it helps.

---
Tags: 8, theming
---


# Question
Title: Node add form set entity reference default selection based on content from another type node
I wrote module with *hook\_form\_alter* to modify *node\_forum\_form*, i.e., node/add/forum form. One forum field is a taxonomy entity reference, *field\_topic*. I want to set the *field\_topic* selection based on the value from a specific node (NID=77) of type *current\_topic*, which also has *field\_topic* as an entity ref.

*field\_topic* is ref to Topic taxonomy.

After loading node 77, I got the TID of the *current\_topic field\_topic*, loaded the term, and then got the term name. Name is displayed on the form above the title using `$form['title']['#markup']`.

Problem: Before returning the form, how can I set the form default selection to be that same *field\_topic* value?

```
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id != 'node_forum_form') {
    return FALSE;
  }
  else {
    $nid = 77;
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    $current_topic_id = $node->get('field_topic')->getString(); //get the TID
    $term = Term::load($current_topic_id);
    $the_topic = $term->getName();

    $form['title']['#markup'] = t('<h3>The Current Topic is:  <i>' . $the_topic . '</i></h3>');

    // REPLACE THE NEXT LINE WITH CODE TO SET THE CURRENT TOPIC
    $form['field_topic']['widget']['#options']['_none'] = 'Click & Select the Current Topic';

    return $form;
  }
}

```

# Answer
> 0 votes
I suppose with

> set the form selection

you mean the default value of the taxonomy term reference field?

If yes, in the code above try this:

```
$form['field_topic']['widget']['#default_value'] = $term->tid();

```

Btw. you also want to change your implementation from `MYMODULE_form_alter` to `MYMODULE_form_node_forum_form_alter`, because the former hook will be called for all forms, whereas the latter is just called when the forum node form renders.

# Answer
> 0 votes
The $term-\>tid() was calculated earlier in the code. That was the solution.

---
Tags: 8, hooks
---


# Question
Title: I can't remove comma after currency in commerce price
In my project I had to change currency code from USD to IRR (Iranian Rial)

but in Persian language after currency, there is always a "," character in rendered price (in price component or formatted amount).

Anyone knows how can we get rid from this comma.

# Answer
> 0 votes
In `commerce.currency.inc` the currency is defined as:

```
'IRR' => array(
  'code' => 'IRR',
  'numeric_code' => '364',
  'symbol' => 'REMOVED_DUE_TO_SE_ERROR',
  'name' => t('Iranian Rial'),
  'symbol_placement' => 'before',
  'symbol_spacer' => ',',
  'code_placement' => 'hidden',
  'minor_unit' => t('Rial'),
  'major_unit' => t('Toman'),
  'decimals' => 0,
),

```

If you wanted to override this and set the `thousands_separator` (not present) to and empty string. You can do this in `hook_commerce_currency_info`, documented here http://cgit.drupalcode.org/commerce/tree/commerce.api.php?h=7.x-1.x#n11

You need to set it as, let's say `''` because the defaults are the following for missing properties:

```
  $defaults = array(
    'symbol' => '',
    'minor_unit' => '',
    'decimals' => 2,
    'rounding_step' => 0,
    'thousands_separator' => ',',
    'decimal_separator' => '.',
    'symbol_placement' => 'hidden',
    'symbol_spacer' => ' ',
    'code_placement' => 'after',
    'code_spacer' => ' ',
    'format_callback' => '',
    'conversion_callback' => '',
    'conversion_rate' => 1,
  );

```

---
Tags: commerce
---


title: When does hook_menu run?

text:
# Question
Title: When does hook_menu run?
I need to edit the hook\_menu function in my module. I need to add a new link to a menu, and edit the path for an existing link. Is this possible without creating a whole new module?

The only example in the docs for when hook\_menu runs is when the module is enabled. Is there any other time it runs?

# Answer
Clearing the cache the menu and routing tables will be reconstructed.

In the admin UI, go to:

`/admin/config/development/performance`

Using drush:

```
drush cache-clear all

```

Other methods are described here: How do I call the menu\_rebuild function in Drupal 7?
> 1 votes

---
Tags: 7, hooks, routes
---


# Question
Title: How can I return HTML form in BlockBase build function?
I include some form from API. And I want to include it in block, using `Drupal\Core\Block\BlockBase`. My function return HTML tags, that has tag `<form>`.

But function `build()` return empty array.

```
$element = array(
  '#markup' => $html
);
return $element;

```

# Answer
You will have to include your tags in the `#allowed_tags`, because this markup is filtered in Xss::filterAdmin.

```
$element = [
  '#markup' => $html,
  '#allowed_tags' => ['form', 'input', ...]
];
return $element;

```
> 1 votes

---
Tags: 8, forms, blocks
---


title: html.tpl.php for a View (machine_name)?

text:
# Question
Title: html.tpl.php for a View (machine_name)?
how can I assign my own **html.tpl.php** to a view (machine\_name) via a preprocess-function (template.php) or a hook?

If my view is called "foo\_view\_machine\_name\_bla", which contains 50 views-pages with path, I would like to have a "html--foo\_view\_machine\_name\_bla.tpl.php".

I do not know songs how to do that.

Can someone help me please.

# Answer
> 0 votes
If I understand you correctly you are wanting to create a specific 'view' template file, your initial question is not clear. You also don't mention which Drupal version you are using. I will assume it's Drupal 7. Go to your specific view and click Advanced then select Theme. There is a list of file names used for the view. The highlighted templates are current. After is a list of suggested templates that can be used. It's quite safe to use the first example. Copy the highlighted file from core and save it to your themes/templates folder rename it to the suggested file name. Clear cache and revisit the same view \> Advanced \> themes section. Your new template file should now be highlighted. That's it! You are now control of the output. Edit the file as you wish.

---
Tags: 7, views, hooks
---


# Question
Title: Can I add CSS to a YAML generated page ?
(Sorry if that's Drupal 101, but I'm still at the very bottom of the learning curve ..)

I have a custom module, with a routing file that redirects to a path that I have chosen arbitrarily :

```
grefsearch:
  path: 'solr-search/content'
  defaults:
    _controller: '\Drupal\gref\Controller\GrefSearchController::search'
  requirements:
    _permission: 'use gref search'

```

I have another YAML config which describes the View that must be rendered when accessing to `solr-search/content` :

```
langcode: en
status: true
dependencies:
...
page_1:
    display_plugin: page
    id: page_1
    display_title: Page
    position: 1
    display_options:
      display_extenders: {  }
      path: solr-search/content
      cache:
        type: none
      defaults:
        cache: false
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
      cacheable: false
      max-age: -1
      tags:
        - 'config:field.storage.node.body'

```

Since the page is completely YAML-based, I do not have a Twig template that is linked to it, and because of that, I cannot use hooks like `template_preprocess_page` because I cannot name the function properly.

I'm a bit lost. Should I change the structure I have, and render the page in a Twig template anyway ? Thanks !

# Answer
> 0 votes
You can still use the hook\_preprocess\_page for a specific path like this:

```
/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_page().
 *
 * @param $variables
 */
function mymodule_preprocess_page(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  if ($current_path === '/solr-search/content') {
    $variables['#attached']['library'][] = 'my_module/my-css-library';
  }
}

```

---
Tags: 8, theming
---


# Question
Title: grabbing data and displaying it in block twig
bI made a custom module and made a custom block inside of it.

In the build () I have this.

```
return array (
  '#theme' => 'no_athlete_match_block',
  '#title' => 'Athletes With No Matching Name in the Database',
  '#description' => 'Displays the athletes with no matching name in the database for a given sporting event.',
);

```

In the .module file I have this.

```
function no_athlete_match_theme($existing, $type, $theme, $path) {
  return array(
    'no_athlete_match_block' => array(
      'variables' => array(
        'description' => NULL,
        'title' => NULL
      ),
      'template' => 'block--no_athlete_match',
    ),
  );
}

```

my twig file named block--no-athlete-match.html.twig

```
<div>
node: {{title}} {{description}}

```

Only Node: shows up. If I do dump(title) I get NULL to show up. Not sure what I'm missing. I've copied other blocks and still nothing.

# Answer
So having playing around with it for two days I ended up commenting out template and listening to the twig debug recommendations. I then added the path so that I could have the template in my module folder. It might not be the best way to do this but it's working.

My module function

```
function no_athlete_match_theme($existing, $type, $theme, $path) {
return array(
 'no_athlete_match_block' => array(
          'variables' => array(
              'dsp' => NULL,
              'title' => NULL,
          ),
       //  'template' => 'no-athlete-match',
         'path' => drupal_get_path('module', 'no_athlete_match') . '/templates'
      )
);

```

}

My block file

```
 return array (
            '#theme' => 'no_athlete_match_block',
            '#title' => 'Athletes With No Matching Name in the Database',
            '#description' => 'Displays the athletes with no matching name in the database for a given sporting event.',
            '#dsp' => $output,
        );

```

My Twig file.

```
<div>
    <table>
        <tr>
            <th>Player</th>
            <th>Query</th>
        </tr>
        <tr>
            <th>{{dsp.player}}</th>
            <th><small>{{dsp.notes}}</small></th>
        </tr>
    </table>
</div>

```
> 0 votes

# Answer
Because you've specified the `template` parameter in the hook\_theme function the template file name should be exactly as specified `block--no_athelete_match.html.twig`. The underscores are converted to dashes only in the case where the `template` parameter is not specified in the hook\_theme function.
> 0 votes

# Answer
In your module file the suggestion of template will be only with underscores.

`block__no_athelete_match`

and in templates folder template name needs to be only with dashes.

`block--no-athelete-match.html.twig`
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Error 404 when upload image in profile installation
I am installing a custom distribution, I have created a form:

`my_distribution.install:`

```
/**
 * Implements hook_install_tasks().
 */
function my_distribution_install_tasks(&$install_state) {
  $tasks = [
    "extra_configs" => [
      "display_name" => t("Extra configurations"),
      "type" => "form",
      "function" => "Drupal\my_distribution\Form\ExtraConfigsForm",
    ]
  ];

  return $tasks;
}

```

`Drupal\my_distribution\Form\ExtraConfigsForm.php:`

```
// more code ...

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#title'] = $this->t('Extra configurations');

    $form['logo'] = [
        '#type' => 'managed_file',
        '#title' => t('Load logo'),
        '#upload_location' => 'public://logo/',
        '#upload_validators' => [
          'file_validate_extensions' => [
            'png jpg jpeg',
          ],
        ],
        '#required' => TRUE,
      ];

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save and continue'),
      '#button_type' => 'primary',
    ];

    return $form;
}

// more code ...

```

Everything works fine but, when I get to that form and load an image I get an error in the javascript console, and i can't continue:

```
AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 404
Debugging information follows.
Path: /core/install.php/%3Cnone%3E?element_parents=logo&langcode=es&profile=my_distribution&ajax_form=1
StatusText: Not Found
ResponseText: {"message":"No route found for \u0022POST \/core\/install.php\/%3Cnone%3E\u0022 (from \u0022http:\/\/my-distribution.local\/core\/install.php?langcode=es\u0026profile=my_distribution\u0022)"}

```

In watchdog i only see:

```
ID  Date          Type      Severity  Message
79  08/Oct 13:15  page not  warning   /core/install.php/%3Cnone%3E?element_parents=logo&langcode=es&profile=my_distribution&ajax_form=1&_wrapper_format=drupal_ajax

```

Drupal version: 8.5.7

What could be the issue?

# Answer
> 1 votes
Try add:

```
rewrite ^/core/install.php/(.*)$ /core/install.php$1;

```

to the config/nginx/drupal8.conf about line 16.

Adapting from:

https://github.com/kalabox/kalabox/issues/1767

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