title: How to prevent Autocomplete Caching?

text:
# Question
Title: How to prevent Autocomplete Caching?
I have made textfield to be autocomplete field by using hook\_form\_alter.

```
mymoudle_form_alter(&$form, &$form_state, $form_id){
   $form['field_state']['und'][0]['value']['#autocomplete_path'] ='get-state-values';
}
    function mymoudle_drupal_menu() {
    $items = array();

    $items['get-country-value'] = array(
            'title' => 'Country Value',
            'page callback' => '_get_country_value',
            //'page arguments'  => array(1),
            'access arguments' => array('access content'),
            'type' => MENU_CALLBACK,
    );
    $items['get-state-values'] = array(
            'page callback' => '_get_state_values',
            'access arguments' => array('access content'),
            'type' => MENU_CALLBACK
    );
    return $items;
}

function _get_state_values($string){
    $country =$_SESSION['country'];
    if($country == 'India'){
        $state = array('Tamilnadu' => 'Tamilnadu','Karanataka' => 'Karanataka');
    }
    else{
        $state = array('NewYork' => 'NewYork','Manahattan' => 'Manahattan');
    }
    print drupal_json_output($state);exit;
}
function _get_country_value(){
    $country = $_REQUEST['valueSelected'];
    $_SESSION['country'] = $country;
    print drupal_json_output($country);exit;
}

```

If I select **country** as **India** and type in the **state** as '**n**' it shows me in auto-complete as two states with n words like **tamilnadu** and **karnataka** which is correct(it runs ajax to fetch the values as shown in screenshot-1).

The issue over here is if I again change the **country** to '**Us**' and type same '**n**' it shows same set of results and it doesn't run the ajax(as shown in screenshoot-2). Its showing from cache I think for previous results.

**NOTE: I want an fix for the ajax caching issue.**

I have attached the screenshot of what's happening .How to avoid this issue?.Any help will be much appreciated.Thanks in advance.

# Answer
Since, there is no proper way, I opted for hack (or work around) to get this working. As already mentioned by @Clive, removing/disabling caching mechanism would require more work. This solution just skips the caching part.

Step1: Copy the entire misc/autocomplete.js to your module js scripts directory.

Step2: Comment or remove the following line from the copied file

```
// See if this key has been searched for before.
  //if (this.cache[searchString]) {
      // We dont want some things to be cached
    //return this.owner.found(this.cache[searchString]);
  //}

```

Step3: Implement hook\_js\_alter to override it to specific pages you like.

```
/**
 * Implements hook_js_alter
 * @param array $javascript
 */
function MYMODULE_js_alter(&$javascript) {
  if (arg(0) == 'MYPAGE') {
    $javascript['misc/autocomplete.js']['data'] = drupal_get_path('module', 'MYMODULE') . '/js/autocomplete.js';
  }
}

```
> 3 votes

# Answer
Static caching is built in so you'll need to override `Drupal.ACDB.proptotype.search`.

This is untested but should be near the mark:

```
Drupal.ACDB.prototype.search = function (searchString) {
  var db = this;
  this.searchString = searchString;

  // See if this string needs to be searched for anyway.
  searchString = searchString.replace(/^\s+|\s+$/, '');
  if (searchString.length <= 0 ||
    searchString.charAt(searchString.length - 1) == ',') {
    return;
  }

  // THIS IS THE BIT TO REMOVE
  // See if this key has been searched for before.
  //if (this.cache[searchString]) {
    //return this.owner.found(this.cache[searchString]);
  //}

  // Initiate delayed search.
  if (this.timer) {
    clearTimeout(this.timer);
  }
  this.timer = setTimeout(function () {
    db.owner.setStatus('begin');

    // Ajax GET request for autocompletion. We use Drupal.encodePath instead of
    // encodeURIComponent to allow autocomplete search terms to contain slashes.
    $.ajax({
      type: 'GET',
      url: db.uri + '/' + Drupal.encodePath(searchString),
      dataType: 'json',
      success: function (matches) {
        if (typeof matches.status == 'undefined' || matches.status != 0) {
          db.cache[searchString] = matches;
          // Verify if these are still the matches the user wants to see.
          if (db.searchString == searchString) {
            db.owner.found(matches);
          }
          db.owner.setStatus('found');
        }
      },
      error: function (xmlhttp) {
        alert(Drupal.ajaxError(xmlhttp, db.uri));
      }
    });
  }, this.delay);
};

```

That will change the behaviour site wide (or for the entire context in which you include the above snippet). To override for certain URIs you'll probably need to get a bit cleverer and monkey patch a few more core JS methods.

Also note that this doesn't disable caching, it just stops cached results from being returned instead of making the ajax call each time. To properly remove caching would require a bit more work.
> 2 votes

# Answer
The cache is saved in a property of ACDB object, unfortunately we can't access the instances of this object. However we can override the search function prototype object of Drupal.ACDB in order to delete this cache before every query.

Overriding Drupal.ACDB prototype will affect all autocompletes in Drupal, so you can minimize the impact (of not having cache) including your override javascript code only in specific pages. Also you can minimize the impact checking for the autocomplete ID or specific class or attribute since (inside the search function) you know which is the input in your DOM.

First you must backup the Drupal.ACDB.prototype.search function:

```
Drupal.ACDB.prototype.search_bkp = Drupal.ACDB.prototype.search;

```

Then you can override search function and apply your logic to erase the cache and then call search again.

```
Drupal.ACDB.prototype.search =
    function (searchString) {
        // your autocomplete element in DOM
        // use it like $(this.owner.input) to access jQuery functions
        console.log( 'AC =', this.owner.input );

        // Deleting the cache, apply your logic
        // ej. if ($(ac.owner.input).attr('id') === 'my-id-of-the-ac-input') {}
        this.cache = {};
        this.search_bkp(searchString);
};

```

Finally, you can execute the code above "whenever you want" (after Drupal.ACDB definition)... you can even try it in the Chrome console.

Hope that helps.
> 2 votes

# Answer
I think your problem lies in how you are setting the session variable. Cache has nothing to do with it.

Drupal only needs to retrieve the values for the fields once to render the form on the server side. Your code doesn't throw any errors because the country field is rendered before the state field, so the state field uses the *default* country value (first item in the array) to perform its calculation.

You need some client-side code (JQuery) to refresh the state values via AJAX whenever the country value is changed.

Have a look at Tenken's answer to a very similar question.

I would also consider using a hierarchical taxonomy to store your values rather than hard-coding them as per this documentation page.
> 0 votes

# Answer
I think it is a session issue and session value only reflect after reload the page.
> 0 votes

# Answer
I had a similar problem I created an entity reference field, and then I wanted to have custom autocomplete result list based on another field value (for example a select box). I managed to pass the select box value as filter parameter to the custom drupal autocomplete\_path handler(at the backend). The problem if I searched for "a" and select "val1" from the select box I will get some result list,but if I changed the select box value to "val2" and type the same search character "a" I will get result list related to "val1". It will not send an ajax call again because it is cached. So after many days of search I found a solution that resolved my problem, and that is by overriding the "Drupal.ACDB.prototype.search" I found the solution here :https://knackforge.com/blog/sujith/ajax-autocomplete-customization-textfield-drupal
The solution suggested @Clive works fine,I tested and it works.
> 0 votes

---
Tags: caching, ajax, 7
---


# Question
Title: Why am I getting Your system schema version is -1
I'm trying to make database updates to my Drupal 8 website, but I keep getting the error `Your system schema version is -1. Updating directly from a schema version prior to 8000 is not supported.`, therefore I can't make the updates. I already have the line `const CORE_MINIMUM_SCHEMA_VERSION = 8000;` in core/lib/Drupal.php. Why am I getting this error?

The full error is as below:

```
[error]  Your system schema version is -1. Updating directly from a schema version prior to 8000 is not supported. You must upgrade your site to Drupal 8 first, see https://www.drupal.org/docs/8/upgrade. (Currently using Minimum schema version The installed schema version does not meet the minimum.)

 Requirements check reports errors. Do you wish to continue? (yes/no) [yes]:
 >

 ------------------------- ----------------------------------------------- ------------- -------------------------------------------------------------------------------------------------------------------------------------------------
  Module                    Update ID                                       Type          Description
 ------------------------- ----------------------------------------------- ------------- -------------------------------------------------------------------------------------------------------------------------------------------------
  address                   clear_country_list                              post-update   Clear caches to receive the new country list.
  address                   convert_names_subdivisions                      post-update   Re-save all entities with address data to update names and subdivisions.
  adminimal_admin_toolbar   avoid_custom_font                               post-update   Update adminimal_admin_toolbar.settings to include avoid_custom_font.
  block_content             add_views_reusable_filter                       post-update   Adds a 'reusable' filter to all Custom Block views.
  block                     disable_blocks_with_missing_contexts            post-update   Disable all blocks with missing context IDs in block_update_8001().
  block                     disabled_region_update                          post-update   Disable blocks that are placed into the "disabled" region.
  block                     fix_negate_in_conditions                        post-update   Fix invalid 'negate' values in block visibility conditions.
  comment                   enable_comment_admin_view                       post-update   Enable the comment admin view.
  commerce_cart             1                                               post-update   Revert Cart views to fix broken Price fields.
  commerce_cart             2                                               post-update   Revert the cart block and form views.
  commerce_checkout         1                                               post-update   Revert Checkout views to fix broken Price fields.
  commerce_log              1                                               post-update   Revert the Activity view to make the date column sortable.
  commerce_log              2                                               post-update   Revert the Activity view to change page limit and ordering.
  commerce_order            1                                               post-update   Revert Order views to fix broken Price fields.
  commerce_order            2                                               post-update   Update order types.
  commerce_order            3                                               post-update   Revert the Order and Profile entity view displays.
  commerce_order            4                                               post-update   Revert the Order entity view displays.
  commerce_order            5                                               post-update   Revert the Order entity form display.
  commerce_order            6                                               post-update   Update the profile address field.
  commerce_order            7                                               post-update   Revert the 'commerce_order_item_table' view - empty text added.
  commerce_order            8                                               post-update   Unlock the profile 'address' field.
  commerce_order            9                                               post-update   Grants the "manage order items" permission to roles that can update orders.
  commerce_payment          1                                               post-update   Re-save payment methods to populate the payment_gateway_mode field.
  commerce_payment          2                                               post-update   Re-save payments to populate the payment_gateway_mode and completed fields.
  commerce_product          1                                               post-update   Revert the Products view because of the updated permission.
  commerce_product          2                                               post-update   Revert the default order item form display.
  commerce_product          3                                               post-update   Revert the default order item form display.
  commerce_product          4                                               post-update   Expose the status field on every product form.
  commerce_product          5                                               post-update   Enable the "Duplicate" variation button for every product type.
  commerce_product          6                                               post-update   Grants the "manage variations" permission to roles that can update products.
  commerce_product          7                                               post-update   Move the variations form to its own tab.
  commerce_promotion        1                                               post-update   Add the coupons field to orders.
  commerce_promotion        2                                               post-update   Add the 'promotion_id' field to coupons.
  commerce_promotion        3                                               post-update   Delete orphaned coupons.
  commerce_promotion        4                                               post-update   Add the compatibility field to promotions.
  commerce_promotion        6                                               post-update   Update offers and conditions.
  commerce_promotion        7                                               post-update   Add the condition_operator field to promotions.
  commerce_promotion        8                                               post-update   Re-save promotions to populate the condition operator field.
  commerce_promotion        9                                               post-update   Update offers and conditions.
  commerce_store            1                                               post-update   Revert the Stores view because of the updated permission.
  commerce_store            2                                               post-update   Revert the Stores view.
  contextual                fixed_endpoint_and_markup                       post-update   Ensure new page loads use the updated JS and get the updated markup.
  dblog                     convert_recent_messages_to_view                 post-update   Replace 'Recent log messages' with a view.
  editor                    clear_cache_for_file_reference_filter           post-update   Clear the render cache to fix file references added by Editor.
  field                     email_widget_size_setting                       post-update   Adds the 'size' setting for email widgets.
  field                     entity_reference_handler_setting                post-update   Fixes the 'handler' setting for entity reference fields.
  field                     remove_handler_submit_setting                   post-update   Remove the stale 'handler_submit' setting for entity_reference fields.
  field                     save_custom_storage_property                    post-update   Re-save all field storage config objects to add 'custom_storage' property.
  image                     image_style_dependencies                        post-update   Saves the image style dependencies into form and view display entities.
  image                     scale_and_crop_effect_add_anchor                post-update   Add 'anchor' setting to 'Scale and crop' effects.
  language                  language_select_widget                          post-update   Add the 'include_locked' settings to the 'language_select' widget.
  locale                    clear_cache_for_old_translations                post-update   Clear cache to ensure plural translations are removed from it.
  node                      configure_status_field_widget                   post-update   Load all form displays for nodes, add status with these settings, save.
  node                      node_revision_views_data                        post-update   Clear caches due to updated views data.
  system                    add_region_to_entity_displays                   post-update   Update entity displays to contain the region for each field.
  system                    change_action_plugins                           post-update   Change plugin IDs of actions.
  system                    change_delete_action_plugins                    post-update   Change plugin IDs of delete actions.
  system                    classy_message_library                          post-update   Clear caches to ensure Classy's message library is always added.
  system                    extra_fields                                    post-update   Update all entity displays that contain extra fields.
  system                    field_formatter_entity_schema                   post-update   Clear caches due to schema changes in core.entity.schema.yml.
  system                    field_type_plugins                              post-update   Force field type plugin definitions to be cleared.   @see https:www.drupal.orgnode2403703
  system                    hashes_clear_cache                              post-update   Force caches using hashes to be cleared (Twig, render cache, etc.).
  system                    language_item_callback                          post-update   Force cache clear for language item callback.   @see https:www.drupal.orgnode2851736
  system                    recalculate_configuration_entity_dependencies   post-update   Re-save all configuration entities to recalculate dependencies.
  system                    states_clear_cache                              post-update   Force cache clear to ensure aggregated JavaScript files are regenerated.   @see https:www.drupal.orgprojectdrupalissues2995570
  system                    timestamp_plugins                               post-update   Force plugin definitions to be cleared.   @see https:www.drupal.orgnode2802663
  taxonomy                  clear_entity_bundle_field_definitions_cache     post-update   Clear entity_bundle_field_definitions cache for new parent field settings.
  taxonomy                  clear_views_data_cache                          post-update   Clear caches due to updated taxonomy entity views data.
  taxonomy                  handle_publishing_status_addition_in_views      post-update   Add a 'published' = TRUE filter for all Taxonomy term views and converts  existing ones that were using the 'content_translation_status' field.
  user                      enforce_order_of_permissions                    post-update   Enforce order of role permissions.
  views                     boolean_filter_values                           post-update   Set all boolean filter values to strings.
  views                     bulk_field_moved                                post-update   Update dependencies for moved bulk field plugin.
  views                     cleanup_duplicate_views_data                    post-update   Update some views fields that were previously duplicated.
  views                     entity_link_url                                 post-update   Add additional settings to the entity link field and convert node_path usage  to entity_link.
  views                     field_formatter_dependencies                    post-update   Include field formatter dependencies in a view when the formatter is used.
  views                     filter_placeholder_text                         post-update   Add placeholder settings to string or numeric filters.
  views                     grouped_filters                                 post-update   Rebuild caches to ensure schema changes are read in.
  views                     revision_metadata_fields                        post-update   Fix table names for revision metadata fields.   @see https:www.drupal.orgnode2831499
  views                     serializer_dependencies                         post-update   Fix views with serializer dependencies.
  views                     table_display_cache_max_age                     post-update   Fix cache max age for table displays.
  views                     taxonomy_index_tid                              post-update   Fix views with dependencies on taxonomy terms that don't exist.
  views                     update_cacheability_metadata                    post-update   Update the cacheability metadata for all views.
  views                     views_data_table_dependencies                   post-update   Include views data table provider in views dependencies.
 ------------------------- ----------------------------------------------- ------------- -------------------------------------------------------------------------------------------------------------------------------------------------
 Do you wish to run the specified pending updates? (yes/no) [yes]:
 >

 [notice] Update started: address_post_update_clear_country_list
 [ok] Update completed: address_post_update_clear_country_list
 [notice] Update started: address_post_update_convert_names_subdivisions
 [ok] Update completed: address_post_update_convert_names_subdivisions
 [notice] Update started: adminimal_admin_toolbar_post_update_avoid_custom_font
 [ok] Update completed: adminimal_admin_toolbar_post_update_avoid_custom_font
 [notice] Update started: block_content_post_update_add_views_reusable_filter
 [ok] Update completed: block_content_post_update_add_views_reusable_filter
 [notice] Update started: block_post_update_disable_blocks_with_missing_contexts
 [ok] Update completed: block_post_update_disable_blocks_with_missing_contexts
 [notice] Update started: block_post_update_disabled_region_update
 [ok] Update completed: block_post_update_disabled_region_update
 [notice] Update started: block_post_update_fix_negate_in_conditions
 [ok] Update completed: block_post_update_fix_negate_in_conditions
 [notice] Update started: comment_post_update_enable_comment_admin_view
 [error]  'action' entity with ID 'comment_delete_action' already exists.
 [error]  Update failed: comment_post_update_enable_comment_admin_view
 [error]  Update aborted by: comment_post_update_enable_comment_admin_view
 [error]  Finished performing updates.

```

# Answer
You can reset it with Drush

`drush ev drupal_set_installed_schema_version('system', 8000)`

OR

If you have Devel installed with, you can execute the following PHP Code

```
drupal_set_installed_schema_version('system', 8000);

```
> 1 votes

---
Tags: 8, database
---


# Question
Title: Displaying content based on the field value
I have a view that displays my content of a specific content type that has a image field. I also have a check box field for that content type. My requirement is that i need the content that has the checkbox checked to be displayed at the top of the list in the view. Could someone tell me how to achieve it?

# Answer
Under `Sort criteria` add your check-box field and set it to `Sort ascending` (it may be descending in your case depending on your field values).

Then if you have more than one Sort criteria **Rearrange** them so that the checkbox field comes first, on top. This way the results are first sorted by the check-box field value.

This works independently of the image field. Is your image field tied to the check-box somehow?
> 1 votes

---
Tags: views
---


# Question
Title: Pre-populate webform default values with hook_form_alter
I have a webform (version 4.11 on Drupal 7) that is failing QA test because the javascript validation is not correctly attaching to an empty required form element-- the 'Please fill out this value' tag is going to the top of the screen instead of near the element that failed validation.

So as a work-around, I decided to add a `hook_form_alter` and a new validation callback, to manually perform the validation. I am setting the error messages with `drupal_set_message`.

It turns out that the `$form` and `$form_state` arrays for webforms are apparently different from the typical form. Instead of `$form_state['values']['field_key']`, I found them here: `$form_state['input']['submitted']['field_key']`.

However, I can not figure out where each field's `#default_value` key resides in the `$form` array. I would expect it to be `$form['field_key']`, but it's not there.

How can I pre-populate the default value of form elements in a webform with `hook_form_alter`?

# Answer
I found the values here

```
$form['#node']->webform['components']

```

So for the first component, I would change the value like so

```
$form['#node']->webform['components'][1]['value'] = 'test';

```
> 0 votes

# Answer
You can use the following:

```
$form['submitted']['component_name']['#value'] = 'test';

```
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How can I upload an image for a specific image style?
I'm trying to support retina on my site, so I set up a 2x image style and a 2x responsive image style. Now the generated HTML for images looks something like:

```
<img
    srcset="/sites/default/files/styles/2x/public/2019-01/foobar.jpg?itok=H_4_Z44r 1926w"
    sizes="2x"
    src="/sites/default/files/2019-01/foobar.jpg"
    typeof="foaf:Image" />

```

This image was already uploaded to my site when I made the change to support 2x images, and I noticed that it actually copied the original image over from `/sites/default/files/2019-01/` to `/sites/default/files/styles/2x/public/2019-01/`.

My problem now is that I'd like to update the 2x version from the authoring interface, but I can't find anywhere where I can upload my 2x version. Is this possible?

# Answer
Image styles are “derivatives” - they’re automatically derived from the original image you uploaded. A UI to manipulate those derivatives wouldn’t really make sense, the whole point is that they’re generated automatically.

If you can’t change the way you’re working, as in upload the 2x version as the original, and use a 0.5x image style for desktop, and the original upload for Retina, you could always replace the generated styled image files manually via sFTP or similar. But it would become a pain quite quickly.
> 1 votes

---
Tags: 8, media
---


# Question
Title: Left join query between two custom tables
Hi I'm trying to create a join query between two custom tables. One is `publish_options` with a `pubid` as the primary key. The other is `publish_options_bundles` with a referring field `pubid` to the first table.

The problem I'm having is that the results returned are as such:

```
Array
(
    [0] => stdClass Object
        (
            [__CLASS__] => stdClass
            [pubid] => 51
            [title] => Promote to blog
            [created] => 1549262900
            [modified] => 1549262900
            [bundle] => article
        )

    [1] => stdClass Object
        (
            [__CLASS__] => stdClass
            [pubid] => 51
            [title] => Promote to blog
            [created] => 1549262900
            [modified] => 1549262900
            [bundle] => gallery
        )

    [2] => stdClass Object
        (
            [__CLASS__] => stdClass
            [pubid] => 51
            [title] => Promote to blog
            [created] => 1549262900
            [modified] => 1549262900
            [bundle] => page
        )

)

```

I would like it to return like:

```
(
  [__CLASS__] => stdClass
  [pubid] => 51
  [title] => Promote to blog
  [created] => 1549262900
  [modified] => 1549262900
  [bundles] => [
    page,
    article,
    gallery,
  ]
)

```

The code I've come with is below.

```
$query = $this->connection->select('publishing_options', 'po')
      ->fields('po')
      ->condition('po.pubid', $id);
    $query->leftJoin('publishing_options_bundles', 'pob', 'po.pubid = pob.pubid');
    $query->fields('pob', ['bundle']);

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

```

Any help would be greatly appreciated as I am completely stumped now.

Thank you in advance.

# Answer
I found the way to do what I wanted.

The modified query:

```
    $query = $this->connection->select('publishing_options', 'po')
      ->fields('po')
      ->condition('po.pubid', $id);
    $query->join('publishing_options_bundles', 'pob', 'po.pubid = pob.pubid');
    $query->addExpression('GROUP_CONCAT(DISTINCT pob.bundle)', 'bundles');
    $query->groupBy(['po.pubid']);
    $result = $query->execute()->fetch();

```

I added the `groupBy()` methond and the `addExpression()` method with a `GROUP_CONCAT`

The results:

```
stdClass Object
(
    [__CLASS__] => stdClass
    [pubid] => 51
    [title] => Promote to blog
    [created] => 1549262900
    [modified] => 1549262900
    [bundles] => article,gallery,page
)

```
> 1 votes

---
Tags: 8, database
---


# Question
Title: Display database query results in custom module
I have a custom block and I'm able to update its content using #pre\_render if I'm using basic text.

However I'm unable to print database query results using the same way. Below is my code.

```
function _maintenance_prerender(array $build) {
$build['content']['#markup'] = myDatabaseQuery();
return $build;
}

function myDatabaseQuery() {
  $query = \Drupal::database()->select('menu_link_content_data', 'm');
  $query->condition('m.title', 'Visit');
  $results = $query->execute();
}

```

Is there a special way to print database query results on a custom block?

# Answer
To be able to exploit your result, you should fetch your result with one of the function of the Statement class.

If you use the function fetchAll() for example, you will have an array of objects with all your result.

```
$results = $query->execute()->fetchAll();

```

You can do a function to create your markup with that array.

You can also not use a function from Statement and do a foreach directly on the result generate by the execute() function to create your markup

```
$results = $query->execute();

foreach($results as $res) {
    $markup .= "<tr><td>$res->field_1</td><td>$res->field_2</td></tr>";
}

```

If you want see how is design your array, you can install the module kint (from the devel module) and display your result with

```
ksm($results);

```

Additionnally, to work, your query should have the list of fields it should select.

```
$query->fields('m', ['field_1', 'field_2']);

```
> 2 votes

---
Tags: 8, database
---


title: Can I hide a webform?

text:
# Question
Title: Can I hide a webform?
I would like to pilot a webform for a period of time and have the option to hide it vs. delete if needed. How do you hide a webform from your site?

# Answer
> 4 votes
In Drupal 8, you can archive your webform if it's closed.

To close your webform, go in the settings of your webform in the "Form" tab. You can schedule the closing too.

When it will closed, you will have the option to archive it in the "General" tab of its settings.

---
Tags: webforms
---


# Question
Title: How to display node title using computed field?
I have a computed field (text) where I would like to display the node title.

I tried the following thing but nothing worked.

```
$value = $entity->title;
$entity->title;

```

I referred

1. https://blogs.sulross.edu/lwetterauer/computed-fields/

2. https://stackoverflow.com/questions/14087479/how-do-you-access-the-title-node-module-element-field-in-drupal-7

# Answer
To get the value:

```
$value = $entity->title->value;

```
> 2 votes

# Answer
If your entity is a "content entity type" such as node

try:

```
$entity->getTitle();
or for term $entity->getName();

```

see https://api.drupal.org/api/drupal/core%21modules%21node%21src%21Entity%21Node.php/function/Node%3A%3AgetTitle/8.6.x

or https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/function/Term%3A%3AgetName/8.6.x
> 1 votes

# Answer
Two lines should do it (set $id to the node you're interested in)

```
$nodeload = \Drupal\node\Entity\Node::load($id);
$title = $nodeload->getTitle();

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Different Status Message templates for different pages
I have been trying to use different status message templates. But I do not know if we can use different status message templates for different pages. Is it possible?

Right now, I am using

```
status-messages.html.twig

```

Any help would highly be appreciated. Thanks!

# Answer
> 3 votes
Here is an example adding routename to status messages' templates suggestions (you may also add some parameters or whatever you need)

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function HOOK_theme_suggestions_status_messages_alter(array &$suggestions, array $variables) {
  $route = \Drupal::routeMatch();
  $suggestions[] = 'status_messages__'.str_replace('.','_', $route->getRouteName());
}

```

This way you can have `status-messages--[routename].html.twig` as a template, and if this file not exists, have a fallback to `status-messages.html.twig`

---
Tags: 8, status-messages
---


title: Print Menu block Title and the menu

text:
# Question
Title: Print Menu block Title and the menu
* In `admin/structure/menu` I created a menu
* In `admin/structure/block` I created a 'menu block' with above menu

With below code I am able to render the menu in `page--front.tpl.php`

```
<?php
 $block = module_invoke('menu_block', 'block_view', '3');
 print render($block['content']);
?>

```

But how do I render the Menu block Title?

# Answer
> 2 votes
Your implementation is right but you are missing the print subject, you only print the content of the block.

if you debug the $block variable you will find 'subject' as key with value or without value based on the block if it has a title or not.

So your code should be like this in order to print the title.

```
 $block = module_invoke('menu_block', 'block_view', '3');
 print render($block['subject']);
 print render($block['content']);

```

# Answer
> 0 votes
This renders it correctly, including all markup.

```
    $block = block_load('menu', 'menu-my-profile');
    $block = _block_render_blocks(array($block));
    $block = _block_get_renderable_array($block);
    print render($block);

```

---
Tags: 7, theming, blocks
---


# Question
Title: Rename a taxonomy vocabulary during migration
I'm working on a custom migration for taxonomy vocabulary and I was wondering if there is a way to rename a vocabulary during migration? my d7 vocabulary name is `staff` and I wanted to be migrated to d8 as `departments`

# Answer
This could be achieved by using static\_map plugin:

```
plugin: static_map
  bypass: true
  map:
    staff: departments

```
> 0 votes

---
Tags: 8, migrations
---


# Question
Title: Custom content entity route or url alias
I'm not certain if I'm over-complicating something or just missing something or other.

Essentially, and in addition to a separate admin view of my custom entities, I want to assign a URL to them at the root of the site (i.e. /entity01).

I tried creating a URL property, but getting a route to respond to that is proving challenging. I tried adding a route like:

```
my_entities.entity_page:
  path: '/{entity_url}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::view'
    _title: 'Hello'
  options:
    parameters:
      entity_url:
        type: entity_url
  requirements:
    _permission: 'access content'

```

I have a custom a custom parameter converter set up as in:

https://www.drupal.org/docs/8/api/routing-system/implementing-custom-parameter-converters

... and in the `convert` method, I can use an injected service to load my entity, etc. But in the `applies` method, I would like to see if it even matches any of my entities and return true or false appropriately, but the `applies` method doesn't seem to have the value of the URL parameter like the `convert` method does.

And even if I solve that, the above example only works with a path like:

```
path: '/my/{entity_url}'

```

If I remove the `/my` it doesn't work - I assume because it is conflicting with another route?

Thanks for any help!

# Answer
> 4 votes
I think you can do this with the pathauto (path alias?) module. Go to the Admin -\> Config -\> Search / Metadata -\> URL Aliases. In the settings tab, enable your custom entity type.

When you edit them, you should have a URL field added. You can also use the patterns to define default paths if you want.

I did a quick test with an ECK custom entity and it worked.

---
Tags: 8, entities, routes
---


# Question
Title: Let Composer place a Git repo into a custom path
How to place git repo to a custom path? I am using composer/Installer. and I have develop a module on git repo. I would like to add it to composer.json but after pull it should be placed web/modules/custom directory. How can i do that.

I added this parts in my composer.json

```
"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/miteshmap/axelerant_custom"
    }
],

"require": {
    "miteshmap/axelerant_custom": "*"
},
"extra": {
    "installer-paths": {
        "web/core": ["type:drupal-core"],
        "web/modules/contrib/{$name}": ["type:drupal-module"],
        "web/modules/custom/{$name}": ["type:drupal-module"],
        "web/profiles/contrib/{$name}": ["type:drupal-profile"],
        "web/themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"]
    }
}

```

# Answer
```
"require": {
    "composer/installers": "dev-master",
    "miteshmap/axelerant_custom": "*"
},
"extra": {
    "installer-paths": {
        "web/core": ["type:drupal-core"],
        "web/modules/contrib/{$name}": ["type:drupal-module"],
        "web/modules/custom/{$name}": ["type:drupal-custom-module"]
        "web/profiles/contrib/{$name}": ["type:drupal-profile"],
        "web/themes/contrib/{$name}": ["type:drupal-theme"],
        "web/themes/custom/{$name}": ["type:drupal-custom-theme"]
        "drush/contrib/{$name}": ["type:drupal-drush"],
    }
}

```

We can do that when composer/installers have defined the type and for that a request was merged with master here - https://github.com/composer/installers/pull/269

And to add the new merge of composer/installers into your json. you can update the composer.json as per the The solution proposed here - https://github.com/drupal-composer/drupal-project/pull/118. The same is explained in above code.
> 0 votes

# Answer
Using `davidbarratt/custom-installer` you can simply install any repo you want into any custom location you want by assigning it a totally custom type. In the sample below I used the custom types `"type": "foo-bar-foo"` and `"type": "bar-foo-bar"` to install two repos into two different custom locations.

Here's a working sample `composer.json`:

```
{
    "name": "myproject",
    "description": "myproject description",
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "select2",
                "version": "4.0.3",
                "type": "foo-bar-foo",
                "source": {
                    "url": "https://github.com/select2/select2.git",
                    "type": "git",
                    "reference": "tags/4.0.3"
                }
            }
        },
        {
            "type": "package",
            "package": {
                "name": "scrollmagic",
                "version": "v2.0.5",
                "type": "bar-foo-bar",
                "source": {
                    "url": "https://github.com/janpaepke/ScrollMagic.git",
                    "type": "git",
                    "reference": "tags/v2.0.5"
                }
            }
        }
    ],
    "require": {
        "davidbarratt/custom-installer": "^1.0@alpha",
        "scrollmagic": "^2.0",
        "select2": "^4.0"
    },
    "extra": {
        "custom-installer": {
            "foo-bar-foo": "web/themes/custom/mytheme/lorem-ipsum/{$name}",
            "bar-foo-bar": "web/themes/custom/mytheme/dolor-sit-amet/{$name}"
        }
    }
}

```
> 0 votes

---
Tags: composer
---


# Question
Title: How to delete a vocabulary terms programmatically?
I want to remove all the terms from a vocab but not delete the vocab itself.

I can do it on the database, but Id rather use the api if available in D8.

```
$existingTerms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('mycustomvocab');
foreach ($existingTerms as $existingTerm) {
  // Delete vocabulary term *** This function is not available in D8 ***
  taxonomy_term_delete($existingTerm->tid);

  // Delete vocabulary - *** Not what is required ***
  /*
  $vocab = Vocabulary::load($existingTerm->vid);
  if (!is_null($vocab)) {
    $vocab->delete();
  }
  */
}

```

This is how Im doing it at the moment until I find a better solution

```
db_query("DELETE FROM {taxonomy_term_hierarchy} WHERE `tid` IN (SELECT tid FROM {taxonomy_term_data} WHERE `vid` = :ctype)", array(':ctype' => 'mycustomvocab'));
db_query("DELETE FROM {taxonomy_term_field_data} WHERE `vid` = :ctype", array(':ctype' => 'mycustomvocab'));
db_query("DELETE FROM {taxonomy_term_data} WHERE `vid` = :ctype", array(':ctype' => 'mycustomvocab'));

```

# Answer
```
  $tids = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', 'mycustomvocab')
    ->execute();

  $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
  $entities = $controller->loadMultiple($tids);
  $controller->delete($entities);

```
> 23 votes

# Answer
Just noting another approach to delete the taxonomy term individually, useful for some cases:

```
// Example to load and delete a taxonomy term
$tid = 12;
if ($term = \Drupal\taxonomy\Entity\Term::load($tid)) {
  // Delete the term itself
  $term->delete();
}

```
> 3 votes

# Answer
\*If you have access to Drupal Shell run following commands : `drupal shell`

\*Then copy and paste following

```
function truncate_vocab($vid){
    $tids = \Drupal::entityQuery("taxonomy_term")->condition("vid",$vid)->execute();
    $controller = \Drupal::entityManager()->getStorage('taxonomy_term');
    $entites = $controller->loadMultiple($tids);
    $controller->delete($entites);
}
$vocabs = taxonomy_vocabulary_get_names();
foreach($vocabs as $vid){
   truncate_vocab($vid);
}

```

I will try to make it a Drupal Shell command in future.
> 1 votes

---
Tags: 8, taxonomy-terms
---


# Question
Title: Search API autocomplete group suggestions
I am using Search API, Search API autocomplete and Solr search. I'we made a view with an exposed filer that has a funcionality of search api autocomplete.

For now, autocomplete suggestions are just this boring regular template...

Important to notice is also that I am searching two Content Types (Book and Autor)

I would like to implement grouping in my autocomplete suggestion so that my autocomplete looks like this:

**Book:** | **Autor**
Book 1 | Autor n
Book 2 | Autor n
Book 3 | Autor n
Book 4 | Autor n
Book 5 | Autor n
Show all Show all

# Answer
One way to do this requires you to get a bit javaScript-ey

As normal Drupal autocomplete uses "https://jqueryui.com/autocomplete/"

or a wrapper of it see "core/misc/autocomplete.js"

You can do is take 100% control over it. you can add JS to the view and optionally create a controller to handle better "label" : "value"

```
$("#the-id-of-your-search").autocomplete({
      source: function (request, response) {
        var url = '/the-ajax-end-point';
       // or custom Controller returning JasonResponse() :)

       // or custom view with rest Response :)
        $.ajax({
          dataType: "json",
          type : 'Get',
          data: {
            q: request.term
          },
          url: url,
          success: function(data) {
            // play with grouping the data here.
            response( data );
          },
          error: function(data) {
            // do some thing here.
          }
        });
      },
      select: makeSelectAwesome,
      minLength: 3,
    });

   function makeSelectAwesome(e, ui) {
    if (ui && e) {
      if (ui.item) {
        // ui.item.value, ui.item.label
        $("#the-id-of-your-search").val(ui.item.label);
        // in the case of your own controller
        // you can return a whole crap load more stuff
        // Then just label / value
        // Example var data = JSON.parse(ui.item.value);
      }
    }
   }

       // php excerpt for controller ideas
       $request = $this->requestStack->getCurrentRequest();
       $query = $request->get('q');
       /// build a result.
       $value = [
         'type' => $node->getType(),
         'image_url' => $node->field_image ...
         'extra_data_to_make_ui_awesome' => []
       ];

       $results[] = [
         'value' => json_encode($value, TRUE),
         'label' => $node->getTitle(),
       ];
       return new JsonResponse($results, 200);

```

then i guess you just live the dream.
> 0 votes

---
Tags: 8, search
---


# Question
Title: How do I package a distribution on Drupal.org?
I am getting some old and mixed documentation issues with building a release for a Drupal 8-based distribution Drupal.org.

The main documentation is How to package a distribution on Drupal.org, which says to use `drush make` to create a drupal-org.make file. However, when I try to run this command on my site, I get the following error message.

> Make has been removed, in favor of Composer. Use the make-convert command in Drush 8 to quickly upgrade your build to Composer.

That's fine, since I am already using Composer for the project! But how do I actually then publish these dependencies on Drupal.org? Drupal.org is definitely not reading the composer.json file, and building the zip files.

Do I just have to manually make a git tag which includes all the files in the \*vendoré directory, so that Drupal.org knows to build this?

I am running Drush version 9.5.2.

# Answer
> 4 votes
On Drupal.org, there isn't yet support for a distribution composer.json file, as reported on Support for distributions.

The package system used from Drupal.org, to be able to build the package files for a distribution, requires just two files: drupal-org.make and drupal-org-core.make. The latter is only necessary when using a Drupal release that is not official.

If your system doesn't allow you to create a .make file as required from Drupal.org, you can manually create it with any text editor, as long as you use the correct file format (see Example drupal.org make file), and you follow what reported in Drupal.org distribution packaging requirements. In particular, see the notes reported at the beginning.

* External libraries are validated against a whitelist of GPL-compatible libraries since all code distributed from Drupal.org must be GPL compatible
* Git clones from Drupal.org sandboxes (as opposed to full projects) are not supported
* Patches hosted on servers other than Drupal.org are not supported
* Modules and themes hosted on servers other than Drupal.org are not supported
* If you need to specify anything other than an official release of the Drupal core project itself, that needs to go into a separate drupal-org-core.make file
* If you request a specific Git revision you must also define the branch that revision came from

In future, some of those restrictions could be lift. There are feature requests / bugs opened in the packages.drupal.org issue queue.

---
Tags: 8, community-official-site, distributions
---


# Question
Title: Why does the title callback of /user produce the title for /user/register?
I'm a bit puzzled why the title callback of /user produces the title for /user/register and /user/password.

When I set the title callback of /user, I see this affects the title of /user/register and /user/password. However, setting a title callback for /user/register seems to make no difference; it appears to stick to the title callback of /user.

What is special about /user/register and /user/password which results in titles for these callbacks to have their titles produced by the title callback of /user?

```
function mytheme_menu_alter(&$items) {
  $items['user']['title callback'] = 'mytheme_user_title';
}

function mytheme_user_title($title) {
  return 'test';
}

```

# Answer
For the `user/register` title to be changed in a theme:

```
function mytheme_preprocess_page(&$variables) {
  // Only act when the first part of the url equals 'user', the second
  // part is 'register'
  $arg = arg();
  if ($arg[0] == 'user' && $arg[1] == 'register') {
    $variables['title'] = 'Test';
  }
}

```

For the `user/register` title to be changed in a module:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
  drupal_set_title(t('Test'));
  }
}

```

Hope that helps.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How do I render the main navigation menu?
In Drupal 7, we were able to render the main navigation menu onto a page outside the main Drupal folders by including bootstrap.inc and displaying it with this code.

```
 $menuData = menu_tree_output(menu_tree_all_data('main-menu'));
 print drupal_render($menuData);

```

Can something similar be done in Drupal 8?

# Answer
> 0 votes
Here is how to get the render Array :

```
  $menuService = \Drupal::service('menu.link_tree');
  $parameters = $menuService->getCurrentRouteMenuTreeParameters('main');
  $mainMenutree = $menuService->load('main', $parameters);
  $renderArray = $menuService->build($mainMenutree);

```

If needed, here is how to generate the HTML

```
$html = \Drupal::service('renderer')->render($renderArray);

```

Note : replace 'main' by menu name for another one.

---
Tags: 8, external-scripts
---


# Question
Title: Trouble redirecting users after implementing LDAP
We had a feature on our site where we redirected users with certain roles to a particular landing page upon logging in. In a custom module, we implemented `hook_user_login(\Drupal\user\UserInterface $account)` to examine the roles the user had, and redirect them to a particular landing page, depending on the user's roles.

Recently, we installed and configured the `ldap` module, so that users could log on with their LDAP credentials, and Drupal accounts would be auto-generated. However, we quickly found out that users with particular roles were not getting redirected on their very first login. Users belonging to other groups were correctly redirected upon creation of their Drupal account by means of `_hook_user_login()`, so it's strange that it only affects particular groups.

What happens is that, the first time you authenticate with LDAP credentials, the LDAP module creates a new Drupal user after successful authentication, then looks at your LDAP groups and assigns your user corresponding Drupal roles, mapped in the module's configuration.

I haven't been able to figure out why the redirection works for some roles but not others. Obviously, those roles are attaching to the account object earlier in the process than others. But where or why this happens, I haven't been able to figure out.

The second time the user logs in, the Drupal account has the roles at that point, and the redirect (running on `hook_user_login`) happens correctly. I am wanting to say that this works well enough, but my stakeholders want it to work correctly the first time.

My attempt to address the issue was to look at hooks implemented in the LDAP module, and see if any of those give me a user object with all of the assigned roles, from which I can figure out which landing page I should redirect the user to. I couldn't find robust documentation on the hooks, so I implemented each one in a custom module and debugged their arguments to see if any one gave me what I wanted. I found that `hook_ldap_user_edit_user_alter($account, $ldap_user, $context)` gave me an `$account` object. However in testing, at the time the hook fires, the account object only has the role `anonymous`. So, this attempt to use hooks defined in the ldap module seems stymied.

Is there a hook later on in the login/authentication process where I can get a fully fleshed-out user object, with all the roles that the LDAP module is assigning the newly-created user? Or is there another way I can redirect the user?

# Answer
I was not able to find a hook that gave me what I wanted, but as a sort-of work around, I created an event subscriber that uses `checkAuthStatus()` to check the user and path, and redirect when necessary.

This is sub-optimal, because this event fires on every page load, as far as I can tell, but at least we got our feature.
> 0 votes

---
Tags: 8, users, hooks, authentication-authorization
---


# Question
Title: How to alter a link of the language switcher?
I would like to alter the link displayed on the language switcher for the second language of my site, for a certain node. Essentially when you viewing a certain node in the main language, and then use the language switcher to view the secondary language, I want the language switcher to serve a different link from the one that links to the translation of the node on the main language. (The design of this node is different from the one on the main language, so just translating the node won't help in this case)

I've tried both `MYTHEME_preprocess_links__language_block(&$variables)` and `MYMODULE_language_switch_links_alter(array &$links, $type, \Drupal\Core\Url $url)` but in both cases either the variable I was interested was protected or private or I couldn't get any interesting variables to work with.

Is it allowed to use these hooks above for what I'm after, or it needs to be a more hacky way?

# Answer
> 1 votes
To wrap this up, here is the complete solution to this problem.

```
function mytheme_preprocess_links__language_block(&$variables) {
  $internal_path = $variables['links']['ja']['link']['#url']->getInternalPath();

  // In this case 'node/30074' is the translated node that will normally go to
  if ($internal_path == 'node/30074') {

    // We need to create a new Url object with the node we need to redirect to
    $new_internal_path = Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 30073], []);

    // ...and replace the original Url object
    $variables['links']['ja']['link']['#url'] = $new_internal_path;
  }
}

```

Thanks to Clive for pointing out the process for this problem.

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


# Question
Title: How to change the user registration form markup
I want to change the markup on the user registration form that reads

> Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.

and

> A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.

to something more friendly.

I don't think String Overrides works with the registration form so I guess I need a custom module - `hook_form_alter` perhaps?

# Answer
> 2 votes
You can do that by implementing hook\_form\_alter() in your custom module:

For ex:

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    //dpm($form);
    $form['account']['name']['#description'] = t('Your Custom Text');
  }
}

```

To add Markup you should look into theme\_form\_element.

# Answer
> 1 votes
The strings you want to change are the strings used for the #description properties of the *name* and *mail* form fields.

```
  // Only show name field on registration form or user can change own username.
  $form['account']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
    '#required' => TRUE,
    '#attributes' => array(
      'class' => array(
        'username',
      ),
    ),
    '#default_value' => !$register ? $account->name : '',
    '#access' => $register || $user->uid == $account->uid && user_access('change own username') || $admin,
    '#weight' => -10,
  );
  $form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => !$register ? $account->mail : '',
  );

```

You could change those strings by using the String Overrides module (which works for every string passed to `t()`, as in this case), implementing `hook_form_FORM_ID_alter()` in a module, or implementing `hook_form_alter()`.
In the first case, the module would replace every occurrence of the strings, while in the other two cases the strings would be replaced just in a specific form or when other conditions are verified. Since you seem to want to change those strings only when users register their account, I would use `hook_form_FORM_ID_alter()`.

As there users who have the permission to change their own usernames, which means the username is not set when an account is created, I would use code similar to the following one.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && isset($form['#user_category']) && $form['#user_category'] == 'account')) {
    // The user is creating a new account or editing an existing account.
    if (isset($form_state['user']) && $form_state['user']->uid == $user->uid) {
      // The user is creating or editing their own account.
      $form['account']['name']['#description'] = t('Your new description for the name field');
      $form['account']['mail']['#description'] = t('Your new description for the mail field');
    }
  }
}

```

In this way, users who can edit accounts of other users (users with administrative permissions) would see the default description given from Drupal.

# Answer
> 0 votes
There is also the Better Login module which can speed things along for you.

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

---
Tags: 7, users, forms
---


# Question
Title: How to create a multilingual node programmatically?
In the last days I tried to migrate a multilingual CSV file to Drupal 8 without success, so finally I decided to use a Batch Process to accomplish the task.

At this moment I have the batch process working, but at this point I need to create my nodes and create the translation. So, how to create a multilingual node programmatically?

# Answer
Fortunately I found a post named Create and translate a multilingual nodes programmatically.

And here is the code with some comments:

```
use Drupal\node\Entity\Node;

$node = Node::create([
  // The node entity bundle in this case article.
  'type' => 'article',
  //The base language
  'langcode' => 'en',
  'created' => \Drupal::time()->getRequestTime(),
  'changed' => \Drupal::time()->getRequestTime(),
  // The user ID.
  'uid' => 1,
  'title' => 'My test!',
  //If you have another field lets says field_day you can do this:
  //'field_day' => 'value',
  'body' => [
    'summary' => '',
    'value' => '<p>The body of my node.</p>',
    'format' => 'full_html',
  ],
]);
//Saving the node
$node->save();
//This line is not necessary
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/my/path", "en");

//Creating the translation Spanish in this case
$node_es = $node->addTranslation('es');
$node_es->title = 'Mi prueba!';
$node_es->body->value = '<p>El cuerpo de mi nodo.</p>';
$node_es->body->format = 'full_html';
//Saving the node
$node_es->save();
//This line is not necessary
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/mi/ruta", "es");

```
> 20 votes

# Answer
I was racking my brain over this problem in Drupal 8. Here's how I finally got it done, This code copies title, body, all fields, and the pathauto setting. I'm sure there's room for improvement here as some meta fields probably need to get processed too. But this should get you started!

```
// This assumes you have a $node variable that contains the node translation you're starting with
$node_trans = $node->addTranslation('en-au'); // sample using Australian English
$node_trans->setTitle($node->getTitle());
$node_trans_fields = $node->getTranslatableFields();
foreach ($node_trans_fields as $name => $field) {
  if (substr($name, 0, 6) == 'field_' || in_array($name, ['body', 'path', 'title'])) {
    $node_trans->set($name, $field->getValue());
  }
}
try {
  $node->save();
}
catch (\Exception $error) {
  $add_status .= 'ERROR saving ';
}

```
> 4 votes

# Answer
The last part of Adrian's answer didn't work for me.

For the translation part, use:

```
$node->addTranslation('es', ['title' => "Translate title"])->save();

```
> 1 votes

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


title: Can't translate pager labels in View

text:
# Question
Title: Can't translate pager labels in View
I have a view to show post teasers. Inside the view I go to 'translate view' and change the values for tags, date, etc. accordingly. Everything translates fine except the text for 'first' and 'last', which stay in the default language (Spanish) no matter if I switch to English (they stay as 'primera' and 'última'). Every other label works so I'm at a loss here.

Can someone point out if I'm doing something wrong? Maybe I should enable another module but I don't think so. Every other node, block, page and menu works fine in both languages. The problem is just with the mentioned labels.

I'd appreciate any pointers.

# Answer
This seems to be solved by drupal community: https://drupal.org/node/2112281#comment-7971057
> 3 votes

# Answer
These are ui translations, strings inside a t('');

You must install locale module and go to admin/config/regional/translate/translate.

Then add the translations for the pager

Regards.
> 1 votes

# Answer
Instead use the views3 version. There is some real translatable support via i18nviews.

Views provides some kind of pluggable translation system now.
> 0 votes

# Answer
Maybe you just ran into this known issue: https://www.drupal.org/project/views/issues/1794912 The problem occurs in cases where the original language of the view isn't english. Try to do a workaround by implementing `hook_views_pre_render` in a custom module as explained in comment#10.
> 0 votes

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


title: Styling label of a select list

text:
# Question
Title: Styling label of a select list
I want to style the label of my select list with bold font and give it some color.

This is the code for rendering form which I am using in a hook\_block\_view

```
  $form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'City',
    '#options' => $options_first,
    '#prefix' => '<div style="font-weight:bold; color:#FFF">',
    '#suffix' => '</div>',
    '#default_value' => $selected,
    '#ajax' => array(

      'callback' => 'get_citylocations_dropdown',
      'wrapper' => 'dropdown-second-replace',
    ),
  );

```

The #prefix and #suffix is wrapping entire select list and effecting/applying the select list which is not I want. I just want to style the `<label>City</label>` to something like`<label style='my style code goes here'>City</label>`

Its not working as I expected.

How do i do it?

# Answer
> 0 votes
Not sure why you insist on using Form API for this, but form element labels are rendered in `theme_form_element_label()`. You may want to override that function in your theme's template.tpl.php file to produce the desired markup.

# Answer
> 0 votes
Everything in drupal can be themed, form elements can be themed as well. you will need to take these steps:

* First of all introduce your theme function to drupal using hook\_theme
* Then in your code add '#theme' property to your element
* In final step theme your element as you wish in corresponding theme function

a simple code can be like below :

```
function Mymodule_theme() {
  'my_custom_form_element_output' => array(
    'render element' => 'element',
    'template' => 'themes/my-custom-form-element-output',
  );
}

$form['dropdown_first'] = array(
  '#type' => 'select',
  '#title' => 'City',
  '#options' => $options_first,
  '#prefix' => '<div style="font-weight:bold; color:#FFF">',
  '#suffix' => '</div>',
  '#default_value' => $selected,
  '#ajax' => array(
    'callback' => 'get_citylocations_dropdown',
    'wrapper' => 'dropdown-second-replace',
  ),
  '#theme' => 'my_custom_form_element_output',
);

```

and finally in my-custom-form-element-output.tpl.php

```
<label style='my style code goes here'><?php print $element['title]; ?></label>//or something like that, you can check how label is stored in $element using kpr() or dsm()

```

# Answer
> -1 votes
You have to do the styling using CSS, something like `.classname label{ font-weight:bold; color:#FFF; }` . Refer here.

---
Tags: forms, theming
---


# Question
Title: Can a view and a content type share the same alias pattern?
I'd like to have this URL structure on a Drupal 8 site:

```
/schools/usa -> handled by custom view
/schools/europe -> handled by custom view
/schools/school-name -> handled as a normal node

```

So basically when the users makes a request for a URL like /schools/%, Drupal first checks if it finds a node with that alias and, if it doesn't exist, passes on to the view (or vice-versa, view first and then node if the view argument doesn't validate).

Is this achievable?

If I try, the view gets the precedence and throws a 404 on /schools/school-name as "school-name" fails to validate as a taxonomy term (it's a node title after all...)

# Answer
> 2 votes
Yes, you can do this. The key is in the `Action to take if filter value does not validate` option of your Contextual filter.

Set that option to **Display contents of "No results found"**.

Then under `No results behavior` add **Rendered entity - Content** enter `schools/{{ arguments.name }}` or which ever correct token is in your case.

This will make your views work with regular terms, but if the term doesn't validate it will go to the page with the argument. In your case if the argument is `school-name` then it will lead to the node page with that path.

What you should additionally consider is what an argument is entered that isn't neither, a term nor the appropriate part of a node path. You'll just get a blank page with View page title.

Maybe you can solve that by adding another `No results behavior` for that case, maybe a block with a message that the term doesn't exist and a link back to the Views page, then hide the Block on your node pages that share the starting path string.

---
Tags: views, 8, path-aliases
---


# Question
Title: node.html.twig gets cached while other templates do not
I disabled cache with the command

> drupal site:mode dev

I have overridden **html.html.twig** and **node.html.twig**.

If I change something on html.html.twig and refresh the page, the changes take place.

If I change something on node.html.twig and refresh the page, the changes do **not** appear, unless I also clear the cache or edit the node.

If I open the same page with a different browser, changes do take place, but if I make another edit and refresh, it won't work.

So I thought of some kind of browser caching, but clearing the caches in Chrome doesn't help.

How can I force Drupal to re-read node.html.twig without clearing the caches or editing a node everytime?

Thanks!

# Answer
`drupal site:mode dev` won't turn off all the caches. Tunning caching for dev purpose requires manual changes to the `settings.(local.)php`.

Open the `example.settings.local.php` file located in the `sites` directory and copy its content over to site's `settings.(local.)php` file.
Focus on the cache bins - in your case `render` and `dynamic_page_cache`.

```
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```
> 3 votes

---
Tags: 8, theming
---


# Question
Title: How to add google maps js without breaking jquery?
So, I'm trying to implement a custom map using the Google Maps API in addition to a Google Map view. I'm working with an up-to-date D7 install. The reason for this is that I need to have multiple layers of content types, which isn't possible with the default views user interface. The view needs to show multiple entity types as individual layers, which I hope to implement as GeoJSON data layers from GeoJSON views through a custom map implementation.

The problem is my current approach is breaking my existing GMAP views and is interfering with jquery functionality.

I get a series of 'jquery is undefined' errors, as well as broken UI functionality, leading me to believe something is making variables collide.

I am approaching this by creating a block in a custom module and adding the markup and JS necessary through the module like so.

```
add js files $path = drupal_get_path('module', 'gmap_json');
drupal_add_js($path. '/gmap_json.js', 'file');

function gmap_json_block_info() {
    $blocks = array();
    $blocks['hello_world'] = array(
      'info' => t('Hello world'),
    );
    return $blocks;
  }

  function gmap_json_block_view($delta = '') {
    $block = array();
    if ($delta == 'hello_world') {
      $block['subject'] = t('Hello world');
      $block['content'] = t('This is the block content.');
      $block['content'] .= '<div id="json-map"></div>';
    }
    return $block;
  }

```

And my map js is here

```
function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: -28, lng: 137}
    });

    map.data.loadGeoJson(
        'https://storage.googleapis.com/mapsdevsite/json/google.json');
  }

```

The problem seem to be with how I'm adding my scripts, since leaving the `drupal_add_js` statement out of the module is what triggers the error.

So, how am I messing up in adding the js to the page? What's the right way to do this?

# Answer
> 0 votes
So, in this case the answer comes from one of the comments. I wasn't properly using the `drupal_add_js` call, which shouldn't be called globally. So I moved it into the function in my little module to side step this, but the better way to approach this is using the render arrays and the `#attached` property of the block's content array. This approach let's you more granularly choose which js is placed and called.

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


# Question
Title: Within a View, How do i paginate the content found inside a single Multiple file field, i.e. inside one node
Hopefully someone can help.

I am using a file field and allowing unlimited files within a single content type field called "Video", handled by Media Module. I have created a view per "gallery" of multiple files inside the node, it's already set-up contextually using the nid. Paginating the media files list from this one node result isn't easy to do with what is out there. I have tried infinite scroll but it didn't work out, i have also tried CCK Pager with no luck and the limit settings available are just that limits which don't paginate. Any ideas?

Just to be clear i am not trying to paginate a view of nodes, its a view of files found within a single node.

I am using Drupal 7.63

# Answer
There are two obvious ways to solve this, the easier one is through your existing Content views, and the other is through creating a new File type view.

## Content type Views

It is true that the Views type determines what will go into each new row in views results, and Pager is acting on views rows.

But if you have a multi-value field it is possible to make it display each value in a separate views row, making the same node appear many times in the views results, as many times as there are field values.

Here's how you do it:

1. Edit your "Videos" field and under `Multiple field settings` make sure you *don't* have the `Display all values in the same row` option enabled.

This will make the same node repeat as many times as you have videos, and although the Pager will still work on node rows, it will look like it's working on field values (if you're only showing that one field and not revealing the node Title, for example).

## File type Views

To get the Pager to actually page through individual files you have to create File views. There are some steps how you can make that views pull data from one content type and field:

1. The File views starts by displaying file names of all the files on the system. To make it aware of where the file is being used (you want only the Videos) add a Relationship **File: Content using Videos** and make it required. This will filter out only the files that are in the "Videos field", and it will make available various Content related Fields and Filters.
2. Add the "Content: Videos" Field and set it so it doesn't display all values in the same row. You will still see the files repeated in the results.
3. Don't add any File Fields
4. Under `Query settings` enable `Distinct` and `Pure distinct`. This will make each file display only once.
5. Add the Contectual filter for NID, it will be available because of the Relationship you added and it will use it by default.
> 0 votes

---
Tags: 7, views, media, paging
---


# Question
Title: Cannot override template provided by contrib module in theme
I'm leveraging the Superfish module for our menus but need to tweak the output a bit.
Normally I'd just copy the relevant template file (in this case `superfish-menu-items.html.twig`) into my theme and call it a day.
This isn't working in this case. Any ideas why that might be and how to get around it?

Before voting to close this issue, I'd ask that you request information you think would be valuable to providing additional specificity.
I can only assume that this issue is due to some issues with the construction of the Superfish module itself and its theming implementation, so I'm trying to figure out how to work around this.
Any solution would likely be applicable in similar contexts as well.

I've tried modifying the element in `hook_theme()` and `hook_theme_registry_alter()` to point to my theme's implementation of the template, but in both cases I end up hitting

> Twig\_Error\_Loader: Template is not defined errors.

**EDIT:** I'd already enabled debugging prior to posting. Please stop suggesting that I enable debugging. This is what is shown before and after copying the template into my theme. I've cleared caches and verified the template name in my theme.

# Answer
> -3 votes
For drupal8 you need to enable twig debug in the service.yml file. Then clear cache. After that, you will see in the browser inspector all templates name suggestion to override a part of the page.

---
Tags: 8, theming
---


# Question
Title: Image styles not generated during config import
Situation: Drupal 8.6.9 running DrupalVM with Ubuntu 16.04, Apache 2.4.18, Php 7.1.26 with default settings except for the location of the drupal site.

I am trying to do a migration of a Drupal 7 multilingual site to Drupal 8.

Plan is to setup the Drupal 8 site with as much settings and modules as possible so I can alter the content during the migration such as migrating a D7-field to a different D8-field.

I wiped the default DrupalVM drupal site so I can start from scratch. So far I have done a drush site-install with standard profile, enabled some contrib modules that are also in the D7 site (pathauto, search404, etc.) and manually set the necessary settings. One of them is adding the 'field\_image' to the 'Basic Page' content type. I've exported the settings (Config Synchronization) to the config sync directory.

To start from scratch I run a script that does:

```
drush si standard
drush en <various modules installed with composer>
drush cset "system.site" uuid <uuid set in system.site.yml>

```

When I stop here and manually create several page nodes through the UI I can successfully add images and the thumbnails are created accordingly.

When I go on and import the config settings with:

```
drush cim sync --partial

```

Everything is imported succesfully and everything looks fine.

However, when I add the same page nodes through the UI the images are uploaded successfully but the image styles are not created. The 'styles' directory stays empty and the Apache logs show:

```
[Sun Feb 10 20:03:18.426565 2019] [proxy_fcgi:error]
[pid 9432:tid 140423712450304]
(32)Broken pipe: [client 192.168.88.1:59863]
AH01075: Error dispatching request to :
(passing brigade to output filters), referer: http://www.drupalvm.test/node/add/page

```

(error broken in several lines to avoid scrolling)

No errors in php-fpm logs.

The error seems to point to a bug in Apache 2.4/mod\_fcgi, but that has been fixed in 2016.

Also, because the problem occurs after reading in the config settings, not before, I suspect the problem is either related to the config settings or to Drupal itself.

Does anyone have any idea what to check to solve this problem? I'm on this for days now with no success.

# Answer
> 2 votes
I went through adding all the files one by one and finally found the problem:

image.settings.yml contained:

```
suppress_itok_output: true

```

Once it was changed to `false` the problem disappeared.

---
Tags: 8, migrations, configuration
---


# Question
Title: Control Webform's date field (datepicker) from JS
I have to change number of months that's shown in datepicker of my date field in Webform, on desktop I need 2 months, but on mobile just 1.

I'm not able to control that using JS, so I created patch for Webform module to change that and show 2 months.

Is there some solution for this, how I can change stuff like this using JS even I initialized it through field settings in Webform module?

# Answer
You can set default datePicker's options by defining `Drupal.webform.datePicker.options` via the CSS/JS tab.

@see https://cgit.drupalcode.org/webform/tree/js/webform.element.date.js
> 1 votes

# Answer
You can override it with js .. the trick is when it is when your js is attached.

```
so in your module you need ....
<?php
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id){
  if ($form_id === 'webform_submission_YOURFORMID') {
    $form['#attached']['library'][] = 'YOURMODULE/mymodule.fix-datepicker';
  }
}

```

then in your js please try some thing like..

```
(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.fixMyDatepicker = {
attach: function (context) {

  var dateElement = $('#edit-1'); // id of your date picker
  var dateData = dateElement.data();
  if (dateData.datepicker) {
    makeChangesToDatePicker();
  }
  else {
    var myInterv = setInterval(function() {
      if (dateData.datepicker) {
        makeChangesToDatePicker();
        clearInterval(myInterv);
      }
    }, 100);
  }

    function makeChangesToDatePicker() {
      //@TODO here check if mobile .
      var settings = dateData.datepicker.settings;
      settings.maxDate = '2019-03-11';
    }
   }
  };
 })(jQuery, Drupal, drupalSettings);

```

the above worked for me. remember datepicker is just: https://jqueryui.com/datepicker/
> 1 votes

---
Tags: 8, javascript, webforms, datetime
---


# Question
Title: Field group horizontal tabs are displayed as accordions in small screens
On Drupal 8 site using the default Bartik theme, I have setup the article content type to be displayed in **horizontal tabs** based on the "field group" module.

On normal/large screens, the article display page is rendered in **horizontal tabs** style (Good!):

However, in small screens, the article display page is rendered in **accordion** style (Not good!):

I have found an answer here Horizontal Tabs rendered as rendering collapsible fields which is for Drupal 7 and I didn't know how to convert it to work for Drupal 8.

Does anyone have an ideas how to keep the article display rendered as **horizontal tabs** for whatever screen sizes?

# Answer
> 4 votes
Perhaps try out the patch to make this setting configurable as proposed for field\_group module in this issue

Users have reported that it applies cleanly and allows for the setting to trigger based on a custom breakpoint.

Testing it out and reporting success/failure on that issue gives a better chance for this feature to be included into the module itself.

**NOTE:** the patch probably needs to be applied to the dev version of the field\_group module

---
Tags: 8, theming
---


# Question
Title: Why the label of "subject' field in comment-form not be translated and how can I do the translation in a better way?
In the `baseFieldDefinitions` of `Comment` Entity, the `subject` field is set to be translatable, but I can not find such a translation in `User interface translation`(admin/config/regional/translate) that can make it take effect when comment on a content.

```
$fields['subject'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Subject'))
  ->setTranslatable(TRUE)
  ->setSetting('max_length', 64)
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    // Default comment body field has weight 20.
    'weight' => 10,
  ])
  ->setDisplayConfigurable('form', TRUE);

```

I now use the code to translate it in my module:

```
function mymodule_preprocess_form_element(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical') {
    if($variables['label']['#title'] == 'Subject') $variables['label']['#title'] = t('Subject');
  }
}

```

I don't think it's a good way since the translation is already defined.(And I've defined Hook\_Comment\_presave, this two function seems will effect each other,which I don’t want it happen either.)

Is there a better way to do that?

# Answer
> 0 votes
I finally found a solution to enforce translation of 'Subject' label in hook\_form\_alter which can make code more clear:

```
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if($form_id == 'comment_comment_forum_form') {
    $form['subject']['widget'][0]['value']['#title'] = t('Subject');

  }

}

```

---
Tags: 8
---


title: MySQL through SSH tunnel

text:
# Question
Title: MySQL through SSH tunnel
I'm trying to connect my Drupal 8 website to a mysql database hosted on a different server, which is only accessible through SSH. I can connect my database manager (heidiSQL) with a SSH tunnel, but i was wondering if it's possible to connect Drupal via SSH too?

thanks in advance!

Edit; To clear things up a bit: The drupal setup is running localhost on my pc, the database is running on a webserver at our ISP. I could download the database to my pc and connect to it locally, but we're working on this site with multiple developers and want to share just one database so we all have the same data.

Edit 2; The SSH connection is made with a SSH key, so no username/password pair.

# Answer
after some more digging i found a way to connect to the database through an SSH tunnel;

https://www.linode.com/docs/databases/mysql/create-an-ssh-tunnel-for-mysql-remote-access/

I hoped for a solution within the drupal config file (perhaps with some extra extensions) but this will do the trick.
> 0 votes

# Answer
If you can connect to mysql over ssh using another client (like the `mysql` command line client or something like SequelPro) then Drupal should also work with the same settings. I don't have experience with heidiSQL, but I suggest just copying the settings that worked in heidiSQL into your Drupal settings file and see how it goes.

One concern: This might make your page load *very* slow, though, as Drupal makes a lot of queries with each page load and my experience is that the network overhead of mysql-over-ssh is a bit high.
> 2 votes

---
Tags: 8, database, ssh
---


# Question
Title: How do I get a contextual filter argument in a template file?
I use contextual filters for a view whose path is /path/langcode, where *langcode* is a contextual filter. How can I get *langcode* in a template file?

# Answer
> 3 votes
You can get the contextual filter argument from the route match:

```
  $variables['arg_0'] = \Drupal::routeMatch()->getParameter('arg_0');

```

Usually the route parameters of contextual filters are named `arg_0`, `arg_1` etc. If it doesn't work, check the route definition of this View page with Devel (/devel/routes) or Drupal Console.

Dependent on the Twig template you might need to add a cache context as well:

```
  $variables['#cache']['contexts'][] = 'route';

```

---
Tags: 8, views
---


# Question
Title: Node Edit Form and twig template - confusion on where some values come from
I'm still pretty new to Drupal and had a question about the node-edit-form twig template. In them template, you can render {{form}}, {{form.advanced}}, and {{form.actions}} but when using xdebug, the form variable doesn't actually have those values in the array. How are those being processed? I'm curious now i'f I've missed this in other twig templates for other arrays/objects.

# Answer
> 0 votes
VSCode by default sets a limit at ~32 max elements to display in an array so it was truncating the rest. I followed the advice in this post to fix the issue -- which was simply adding the xdebugSettings to the launch.json file in vscode.

```
       {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "xdebugSettings": {
                "max_children": 999,
            }
        }

```

# Answer
> 1 votes
When you xdebug `$variables` in a preprocess hook

```
function mymodule/mytheme_preprocess_node_edit_form(&$variables) {

}

```

you find `$variables['form']['actions']` and the other form elements. You can also install a module to set a breakpoint in the twig template directly, see https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

What you now have is probably the form build `$form` in a different place.

---
Tags: 8, theming
---


title: How do I create a field output URL?

text:
# Question
Title: How do I create a field output URL?
For the multilingual Drupal 8 based website I have created a view with a list of nodes. On the top of the page I have implemented a custom block with a autocomplete textfield, the textfield returns a JSON response with all available languages. After selecting the language, I want to update the fields (titles), so that they are displayed in the language, selected by the user.

The approach I am thinking about is after submitting the textfield, update the fields output. But for this I would need to create some URL for the fields output. How can I create a URL for the fields section with Drupal tools? Is it possible to distinguish the areas on the view? Please, help.

# Answer
> 1 votes
You can not update the output of some part of views from custom block without actually rendering the views again. You have to reload the views using ajax request/ simple http request (as you prefer) with the langcode in views argument.

What you can do is add a global contextual filter in the view, Use that contextual filter's value in template\_preprocess\_views\_\* listed here, If contextual value is not empty.

---
Tags: views, 8
---


# Question
Title: Is it possible to make a "private" distribution not listed on Drupal.org?
For a customer we should do a bunch of sites build with Drupal. Multisite is not possible because of different hosting solutions.

Would creating a custom distribution work out for that case? Is it possible to make a "private" distribution not listed on Drupal.org?

# Answer
> 4 votes
On drupal.org, a distribution is a single download containing Drupal core, contributed modules, themes, and pre-defined configuration. You could create a distribution locally, using the same tools used on drupal.org to create a distribution, but that would involve creating a drupal-org.make file using `drush make`, which is a command removed from Drush.

Instead, as Drush itself suggests, you should use Composer. Create a composer.json file, locally, and add all the dependencies (including modules) you need with `composer require`. If then you need, for example, to create specific content types, roles, taxonomy terms, or other entities, you could create an installation profile, as described in How to Write a Drupal 8 Installation Profile. Using an installation profile doesn't work for already created sites, but for sites you still have to create, a custom installation profile helps in building a site.

As example of what an installation profile can do, see the content of the core/profiles/standard directory, in particular the config directory, which contains the configuration files necessary to create the default entities you normally use on the default Drupal installation. The install/node.type.page.yml file is a configuration file that defines a node content type. (The filename is important for Drupal to understand it's a node content type.)

```
langcode: en
status: true
dependencies: {  }
name: 'Basic page'
type: page
description: 'Use <em>basic pages</em> for your static content, such as an ''About us'' page.'
help: ''
new_revision: true
preview_mode: 1
display_submitted: false

```

An installation profile can have dependencies and a list of core modules that needs to be installed but that aren't dependencies of the profile (see the standard.info.yml file), implement `hook_install()` (see the standard.install file) and other hooks a module can implements, including the one to alter the site configuration form shown during the installation of Drupal (see the standard.profile file).

```
function standard_install() {
  // Set front page to "node".
  \Drupal::configFactory()->getEditable('system.site')->set('page.front', '/node')->save(TRUE);

  // Allow visitor account creation with administrative approval.
  $user_settings = \Drupal::configFactory()->getEditable('user.settings');
  $user_settings->set('register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)->save(TRUE);

  // Enable default permissions for system roles.
  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access comments', 'post comments', 'skip comment approval']);

  // Assign user 1 the "administrator" role.
  $user = User::load(1);
  $user->roles[] = 'administrator';
  $user->save();

  // We install some menu links, so we have to rebuild the router, to ensure the
  // menu links are valid.
  \Drupal::service('router.builder')->rebuildIfNeeded();

  // Enable the Contact link in the footer menu.
  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $menu_link_manager->updateDefinition('contact.site_page', ['enabled' => TRUE]);

  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access site-wide contact form']);

  // Allow authenticated users to use shortcuts.
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access shortcuts']);

  // Populate the default shortcut set.
  $shortcut = Shortcut::create([
    'shortcut_set' => 'default',
    'title' => t('Add content'),
    'weight' => -20,
    'link' => ['uri' => 'internal:/node/add'],
  ]);
  $shortcut->save();

  $shortcut = Shortcut::create([
    'shortcut_set' => 'default',
    'title' => t('All content'),
    'weight' => -19,
    'link' => ['uri' => 'internal:/admin/content'],
  ]);
  $shortcut->save();

  // Allow all users to use search.
  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['search content']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['search content']);

  // Enable the admin theme.
  \Drupal::configFactory()->getEditable('node.settings')->set('use_admin_theme', TRUE)->save(TRUE);
}

```

Installation profiles cannot be changed once Drupal is installed. If you need to use a different installation profile, you need to re-install Drupal. If you aren't creating sites ex-novo, instead of an installation profile, you can create a custom module that you install on existing Drupal sites. A module can still create new entities or entity bundles via configuration files, have code executed when it's installed (via `hook_install()`), and define its dependencies. See, for example, what the Forum module does, for example with its config/optional/node.type.forum.yml file.

```
langcode: en
status: true
dependencies:
  enforced:
    module:
      - forum
name: 'Forum topic'
type: forum
description: 'A <em>forum topic</em> starts a new discussion thread within a forum.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true

```

There are some light differences between a configuration file used from an installation profile and a configuration file. Those differences allow a module to be uninstalled and re-installed, and have its entities (or entity bundles) re-created when the module is re-installed. (Doing differently, re-installing the module would shown an error complaining about the entity existing already.)

# Answer
> 1 votes
As you are deploying the same Drupal sites for different hosting providers, and you may want to install the same modules again and again with same kind of settings. Distribution is the way to manage initial default module dependencies and settings, And you can create your custom distribution and place it in `/profiles` folder.

# Answer
> 1 votes
You can add your own git repositories as sources for composer. This way, you can allow composer to look for code updates in areas other than the standard (public) repositories.

In composer.json, look for the "extra" array, and add a "repositories" item, and then add your own repositories like this:

```
{
    "extra": {
        "repositories": [
            {
                "type": "vcs",
                "url": "..."
            }
        ]
    }
}

```

More info on adding repositories to composer.

You can also configure composer to use private repositories.

---
Tags: 8, distributions, community-official-site
---


title: Link field is removing query parameters

text:
# Question
Title: Link field is removing query parameters
We have an `Article` that a link field, `field_link`. When we create a new page of type `Article`, we set the link field to have a `URL` of `www.example.com/somepath?someid=123345` and label of `View`. When the page is rendered, we are seeing the query parameter is being removed (i.e. `?someid=123345`). We are not doing any `hooks` or extra logic in `twig` templates to remove the query parameters.

How can we prevent the query parameters from being removed when rendering the `field_link` field?

Current behavior when link is rendered:

```
<a href="www.example.com/somepath">View</a>

```

Expected behavior

```
<a href="www.example.com/somepath?someid=123345">View</a>

```

# Answer
> 0 votes
In review, we had the wrong setting for the link. By setting `Both internal and external links`, the link was displaying properly with the `query` parameters.

In Summary

1. `Both internal and external links` should be set on the `field setting`
2. Ensure to use `https://` in the beginning of the `url`

---
Tags: 8, hooks, configuration
---


# Question
Title: How do I use a token to set the default value of a date field to the current date?
When I go to the build tab of the webform and click edit on the date element, I can find the default value setting under the advanced tab in the element editor. The help text says I can use tokens, but I'm having trouble making a token work there. (I'm trying to use the `[current-date:html_date]` token).

If I click "set default value", another dialog opens with a text input and a button that says "update default value". But when I click that button after putting the token into the input, it goes back to the advanced tab and the default value input is empty. If I enter the token before clicking "set default value", the "update default value" dialog opens with an empty input. I've tried various combinations/orders and can't get the token to stay there. It doesn't matter if I type it in, copy/paste it, or fill it using the "browse available tokens" tool.

# Answer
> 2 votes
Leave the "set default value" button alone. *Something about it* makes it seem like a really good button to click for setting a default value, but you don't need it. Just enter the token in the default value input on the advanced tab and click save.

This seems simple enough in hindsight, and I'm not sure why it took so long for it to occur to me to try it. Hopefully if someone else has the same problem, this answer can help save them a few minutes, or perhaps even a longer period of time we won't mention here.

---
Tags: 8, webforms, tokens
---


# Question
Title: Is it possible to add inline css styling to a twig email template?
Is it possible to add inline css styling to a twig email template? Not as a source file reference but by inclusion of css within the template similar to html `<style>...</style>`functionality.

# Answer
> 0 votes
For HTML emails, you have to use the inline style attribute.

The Mimemail module might be able to inline your external CSS.

---
Tags: theming, webforms
---