# Question
Title: Get Entity from Path or Url Object Retrieved from Menu (Node or Page)
Linking through menu link tree elements I'm getting a series of url objects and paths. What I'd like to do is turn those url objects or paths into entities. I want access to the actual entities that they refer to. Here's my code so far:

```
$menu_tree = \Drupal::menuTree();
$menu_parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_id);
$menu_tree_elements = $menu_tree->load($menu_id, $menu_parameters);
foreach ($menu_tree_elements as $menu_tree_element) {
  $menu_tree_link = $menu_tree_element->link;
  $url_object = $menu_tree_link->getUrlObject();
  $path = $url_object->toString();
  $url_params = \Drupal\Core\Url::fromUserInput($path)->
    getRouteParameters();
  var_dump($url_params);
}

```

I was thinking that I could possibly get the entity from the url parameters but I get the error

> External URLs do not have internal route parameters.

Which makes sense to me because I have menu links that refer to just general Page entities not nodes. Like '/about'.

However I'm able to get to the paths just fine. Is there a way that I can load an entity since I have a url object that has a path directly leading to it?

UPDATE: I tried using

```
$params = \Drupal\Core\Url::fromUserInput('/about')->
  getRouteParameters();
var_dump($params);

```

But all that did was return an empty array.

I received the same result when using

```
$params = \Drupal\Core\Url::fromUri("internal:/about")->
  getRouteParameters();

```

# Answer
> 1 votes
I managed to come up with a solution by using the storage manager to load the entity using the path to load it.

```
$page = \Drupal::entityTypeManager()
  ->getStorage('page')
  ->loadByProperties(array(
      'path' => $path
  ));

```

I'm assuming you can use the same method for nodes.

---
Tags: 8, uri
---


title: Include third-party library

text:
# Question
Title: Include third-party library
I have a third party library located in the root/libraries directory, but it is not called on my webpage. I was wondering using subtheme/subtheme.theme or subtheme.libraries.yml. I call it from here? Any information would be great, I can't find documentation on third party libraries for Drupal 8.

# Answer
> 1 votes
You can add your library in your file theme.libraries.yml (or module.libraries.yml) like this:

```
# Parsley use for contact_form.
parsley:
  js:
    dist/js/vendors/parsley.min.js: { minified: true }
  dependencies:
    - core/jquery

```

After, you can include your library like any other libraries with a hook or a template.

---
Tags: javascript
---


# Question
Title: Migrating only articles with a specific taxonomy term
In the source D7, i have a content type 'article' containing a reference to a 'category' taxonomy vocabulary term.

In the target D8, I have a content type 'article' as well, but i only want to import those nodes whose 'category' reference does not equal 'interview' ('interview' is one of its terms).

Also, in the target D8, i have a content type 'interview' to which i want to import all D7's 'article' nodes whose 'category' reference equals 'interview'.

Any ideas how to condition this?

# Answer
Besides setting up a process plugin for the migrate import mapping (via code) as suggested by Berdir in the comments, another option is to setup a views data export on the legacy site to output only the select articles or "interviews".

This approach also allows non-database admins or developers to easily audit the content being migrated (because you can setup an alternative view display as a webpage, or excel spreadsheet, for use as a checklist).

To setup a view in JSON format:

Refer to this StackOverflow answer/post about setting up a JSON view display mode.
> 0 votes

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


title: index doesn't update

text:
# Question
Title: index doesn't update
I'm using Drupal 8's built-in search and it will not update the index.

I have cron running every 15 minutes and even tried running it manually but the search status page always says:

**"0% of the site has been indexed. There are 80300 items left to index."**

Another odd thing is that **some** nodes appear to be indexed, even though the status report says zero, because some (but not all) nodes will appear when searched for.

Any ideas what's going on?

# Answer
This issue is solved. The issue was a malformed URI that was imported from the Drupal 6 website. The search indexing failed when it encountered this content (comment).

It turns out that it was old spam comments from the D6 site. I was able to delete those and indexing is working now.
> 1 votes

---
Tags: search
---


title: Drupal 8 translation for routing titles

text:
# Question
Title: Drupal 8 translation for routing titles
In Drupal 8, I installed all translation modules (Configuration Translation, Content Translation, Interface Translation, Language) and cleared all caches and run cron again.

But the titles defined in routing YML files are still missing from the User interface translation configuration page (/admin/config/regional/translate)

Any idea?

# Answer
> 1 votes
Just figured it out.

After installing all above modules, we still have to visit the page defined by the routing and switch it to another language (non-English).

Then system would automatically pick up all strings in the page needed to translate, including the title.

The source string is case sensitive.

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


# Question
Title: how to alter "other" field label or change the label name
How to alter "other" field label or change the label name Please see the image

Also,

How to constrain the sum of these responses to be 100? Please see the image

# Answer
For customizing the 'more items' see Issue #2953803: Allow multiple value elements item(s) label to be customized.

For 'How to constrain the sum of these responses to be 100?' you are going to have to write custom client-side and server-side validation code.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to return content with shortcodes from drupal module?
I'm using drupal 7 to develop a module.

This module has a menu with a page callback `'page callback' => 'my_function'` and the function has to return HTML.

In the function I'm returning `array('#markup' => $markup);` where `$markup` has HTML with shortcodes: `[button path="node/2" (class="additional class")]Order now[/button]`.

The shortcodes are appearing directly in the browser without transformation. I created a page on the web administration page with the same content and the shortcodes are transformed.

How can I return HTML that has shortcodes from a module?

# Answer
> 0 votes
Shortcodes are processed with a filter, so the most reliable way to get what you need would be:

1. Create a new input format (shortcodes\_only or something)
2. Enable and configure the shortcodes filter for that format, but disable any HTML or other processing that you don't want to apply to your string
3. Process the string before adding it to the render array like so:

```
$markup = check_markup($markup, 'shortcodes_only');

```

If you need to do it programatically it's a bit of a hack, as the shortcode processing code isn't completely decoupled from the filter concept. You need to mock a filter object and give it a couple of properties (a dummy format ID and an array of shortcodes keyed by ID, with a boolean value indicating each shortcode's status).

This is untested but should get you close:

```
$filter = new stdClass();
$filter->format = 'not_a_real_format';
$filter->settings = array_fill_keys(array_keys(shortcode_list_all()), 1);
$markup = _shortcode_process($markup, $filter);

```

If you choose the programmatic method, there's something else to bear in mind: by convention, any function whose name begins with an underscore is considered to be private to the module, and its implementation is subject to change in future releases without warning (potentially breaking your code in unpredictable ways). It's probably not that likely in this case, but you never know.

---
Tags: 7
---


# Question
Title: Drupal 8.5 broken after simultaneously enabling many modules
I installed D8 yesterday, and installed a *bunch* of modules today, then went into the "Extend" window and enabled a lot of them all at the same time (clearly not the best plan). Now all I get on the site is

```
Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "devel.admin_settings" does not exist." at /path/to/drupal/core/lib/Drupal/Core/Routing/RouteProvider.php line 202

```

showing up in the error log. I'm guessing I have to reset the database back to its initial condition. Can I do that without reinstalling Drupal?

# Answer
In the Drupal Slack channel, it was suggested I should try disabling modules using `drush`, starting with *Devel* since that appeared to be where the problem was coming from. After

```
# drush pm-uninstall devel
The following extensions will be uninstalled: devel, ds_devel
Do you really want to continue? (y/n): y
devel was successfully uninstalled.                 [ok]
ds_devel was successfully uninstalled.              [ok]

```

the site's user interface came back to life, and I was able to install all of the modules I had previously selected, including *Devel* and *Display Suite Devel*.

I strongly suspect what happened is the error that terminated the initial attempt to enable modules

```
Maximum execution time of 30 seconds exceeded in /web/spacecolonists/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php on line 1005

```

occrured in the middle of processing the *Devel* installation, which broke it.

This tells me that module installations are not done as a transaction: If they were, the timeout error would have caused the database transaction to fail, resulting in a rollback that left the database in a stable, working state.
> 1 votes

---
Tags: 8, database, installation
---


# Question
Title: How do I update Drush to the latest available version?
On my Mac Mini running OS X 10.11, I installed Acquia Dev Desktop 2 which comes with Drush 8.0.0 rc1. I created a local site which uses Drupal 8, and all went fine; the only problem is that for every Drush command I try, I get an error about a wrong placeholder; the error message gets repeated enough times to make the console output scroll up. For example, with `drush status`, I get the following error messages:

> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !other FormattableMarkup.php:240
> Invalid placeholder: !fields FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !type FormattableMarkup.php:240
> Invalid placeholder: !type FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !type FormattableMarkup.php:240
> Invalid placeholder: !type FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !type FormattableMarkup.php:240
> Invalid placeholder: !type FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !type FormattableMarkup.php:240
> Invalid placeholder: !type FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240
> Invalid placeholder: !default FormattableMarkup.php:240

The command then executes normally, giving me the following output:

> Drupal version : 8.0.0
> Site URI : http://default
> Database driver : mysql
> Database hostname : 127.0.0.1
> Database port : 33067
> Database username : drupaluser
> Database name : tero
> Drupal bootstrap : Successful
> Drupal user :
> Default theme : bartik
> Administration theme : seven
> PHP executable : /Applications/DevDesktop/php5\_5/bin/php
> PHP configuration : /Applications/DevDesktop/php5\_5/bin/php.ini
> PHP OS : Darwin
> Drush script : /Applications/DevDesktop/drush/vendor/drush/drush/drush.php
> Drush version : 8.0.0-rc1
> Drush temp directory : /tmp
> Drush configuration : /Applications/DevDesktop/drush/vendor/drush/drush/drushrc.php
> Drush alias files : /Users/kiamlaluno/.acquia/DevDesktop/Drush/Aliases/aliases.drushrc.php
> Install profile : standard
> Drupal root : /Users/kiamlaluno/Sites/devdesktop/tero
> Site path : sites/default
> File directory path : sites/default/files
> Temporary file directory path : /tmp
> Sync config path : sites/tero.dd/files/config\_05LkLxb13V9Aql8lLTwnzSDjZKUwSM1QqJosn6985ubZ7AvwwnV1j8I6FHt qunj1liphJjAVpw/sync

Still, I would like to avoid these error messages.

How do I update Drush without installing it globally?
I don't want to install it globally because I am using the console Acquia Dev Desktop opens for me, and its Drush takes the precedence over any other command.

# Answer
> 3 votes
These are the commands I have executed from the terminal to update Drush.

```
cd /Applications/DevDesktop/drush
rm -rf vendor/drush/drush
rm -rf vendor/bin/drush*
rm -rf vendor/psy
rm -rf vendor/bin/psysh
composer.phar require drush/drush:8.*

```

I was following Introducing Drush 8 (Composer Users Downloading Stable Versions of Drush), where the suggested command to update Drush (although globally) is `composer global require drush/drush:8.*`. When I tried the following commands, I got an error message.

```
cd /Applications/DevDesktop/drush
composer.phar require drush/drush:8.*

```

The error message was the following one:

> ./composer.json has been updated
> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Your requirements could not be resolved to an installable set of packages.
>
> Problem 1
> \- Conclusion: don't install drush/drush 8.0.1
> \- Removal request for drush/drush == 8.0.0.0-RC1
> \- Installation request for drush/drush 8.\* -\> satisfiable by drush/drush\[8.0.0, 8.0.1, 8.0.0-rc1\].
> \- Conclusion: remove psy/psysh v0.5.2
> \- Can only install one of: psy/psysh\[v0.6.0, v0.5.2\].
> \- Can only install one of: psy/psysh\[v0.6.0, v0.5.2\].
> \- drush/drush 8.0.0 requires psy/psysh ~0.6 -\> satisfiable by psy/psysh\[v0.6.0, v0.6.1\].
> \- Conclusion: don't install psy/psysh v0.6.1|keep psy/psysh v0.5.2
> \- Installation request for psy/psysh == 0.5.2.0 -\> satisfiable by psy/psysh\[v0.5.2\].
>
> Installation failed, reverting ./composer.json to its original content.

# Answer
> 0 votes
Maybe a little old question, but in 2018 we still have problems with that. First go to the tools folder in the DevDestktop

```
cd /Applications/DevDesktop/tools/

```

You can check in the composer.json file wich version do you have, currently drush 8.1.10..

So, for update to the last stable version run the next command:

```
composer require drush/drush 8.1.15

```

You can check your version, by running `drush --version`

---
Tags: drush, 8, acquia-dev-desktop
---


# Question
Title: Can I turn cache off for the development deployment?
On development platform caching can be a pain. Can I turn it off? Will it affect any of the modules that require it?

# Answer
> 20 votes
Install the devel module which adds a cache clear option for administrators. You'll find a devel block to add to a region for quick cache clearing, or if you install the admin menu and get a quick menu in the top left for clearing various caches in Drupal.

If you like the command line install drush and use the `drush cc all` command to clear your sites caches. Beware that currently drush cc doesn't clear the Varnish cache if that's applicable to your setup.

# Answer
> 9 votes
If you are using Drupal 7 you can always set your caching to using DrupalFakeCache, which is normally only used during the installation process. To set that, drop the following code snippet in your settings.php:

```
include_once(DRUPAL_ROOT . '/includes/cache.inc');
include_once(DRUPAL_ROOT . '/includes/cache-install.inc');
$conf['cache_default_class'] = 'DrupalFakeCache';

```

# Answer
> 4 votes
'Performance' page in administration \> site configuration will allow you to enable / disable caching of selected site elements. Theme templates are typically cached more persistently but can be flushed within the same 'performance' page.

'Administration menu' module will provide a shortcut in a toolbar if cache flushes need to be done more regularly - during theme dev I find myself constantly flushing.

# Answer
> 4 votes
As far as I know there aren't any modules that *require* caching. If you don't want to turn it off you can clear it in the `Site Settings > Performance` section.

Even with caching disabled Drupal won't recognise new files added to themes until you clear the cache.

There's a some information on different ways to clear the cache over at Drupal.org

# Answer
> 4 votes
Using the Devel module opens up a few more options, including:

* Rebuilding the theme cache on every page load (This is useful if you're a themer working on template files.)
* A block to provide easy access to the function to empty the cache and the reinstall function

With the Devel module, and cache turned off under *Performance*, the only major cache you'll run into in routine development is the menu router, which can be rebuilt either using the Devel or the Admin Menu module.

# Answer
> 4 votes
One important thing to note is that if you have a lot of stylesheets (either from your theme or from modules), then turning off CSS file optimizing has the potential to break your site in IE.

While not actually caching, it's on the same settings page and is often used with caching.

The "Flush all caches" link in the admin menu module is fantastic, by the way.

# Answer
> 3 votes
If you're using Drupal 6, the "Cache Disable" module can be handy for that task if you do not wish \[for some reason\] to install heavier modules like Devel.

# Answer
> 3 votes
Amount of caches used with Drupal sometimes can get crazy.

Here are the common methods of disabling and clearing Drupal caches and associated with it.

---

**DISABLING CACHES:**

Note that you can't disable all the caches, as some of them are required by Drupal.

Here is a method of disabling the caches by adding the following lines into your settings file:

```
// Disable caches
$conf['cache'] = 0;
$conf['block_cache'] = 0;
$conf['views_skip_cache'] = TRUE;
$conf['page_compression'] = 0;
$conf['preprocess_css'] = 0;
$conf['preprocess_js'] = 0;

```

If you disable all your caches, your website will be very slow, so it's not recommended for any other environments exempt your development machine.

---

**CLEARING CACHES**

**XCache**

Clear XCache caches if used:

```
drush eval "function_exists('xcache_clear_cache') && xcache_clear_cache();"

```

Or clear the cache in XCache in admin panel (/xcache-admin) if above won't work.

**eAccelerator**

```
drush eval "function_exists('accelerator_reset') && accelerator_reset();"

```

**APC**

```
drush eval "function_exists('apc_clear_cache') && apc_clear_cache();"

```

**OPCache**

Clear PHP OPCache if using with PHP \>=5.5

```
drush eval "function_exists('opcache_reset') && opcache_reset();"

```

Note: Above CLI command won't clear cache for Apache, as per: Opcache - Clean cache in PHP5.4 and lower.

**memcached**

If you're using memcached, you should clear, restart or kill your memcached with one of the methods:

As a user (one of these):

```
echo flush_all > /dev/tcp/127.0.0.1/11211
echo flush_all | nc localhost 11211 # Flush Contents Of a Memcached Server

```

As a root (one of these):

```
/etc/init.d/rc.d/memcached restart
service memcached restart
killall memcached # It's automatically restarted on OSX.

```

It is also advised to install memcached module with the following line in your settings file:

```
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';

```

So Memcached caches are cleared on standard Drupal clear cache.

**Varnish**

If you're using Varnish, it's advised to install Varnish module and set the following line in your settings file:

```
$conf['cache_backends'][] = 'sites/all/modules/contrib/varnish/varnish.cache.inc';

```

So Varnish cache would be cleared together on Drupal clear cache.

Alternatively you may use curl for clearing the pages manually:

```
curl -X PURGE -H "Host: domain.com" http://127.0.0.1/node/123

```

Read more: How can I clear the Varnish cache?

**Drupal**

Clear Drupal caches via drush:

```
drush cc all
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v
drush eval 'menu_rebuild();'

```

You may do the same at /admin/config/development/performance, as sometimes UI caches are cleared in the better way than from CLI.

---

Here is the useful shell script for clearing all the caches:

```
#!/bin/bash
set -o xtrace
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v
echo 'flush_all' | nc localhost 11211 # Flush Contents Of a Memcached Server
drush eval "function_exists('opcache_reset') && opcache_reset(); function_exists('xcache_clear_cache') && xcache_clear_cache();"
drush eval 'menu_rebuild();'
set -o xtrace -
echo done.

```

# Answer
> 2 votes
Old question, but I just saw it popped up as a related one to a search I was doing.

Nearly all of the cache clearing methods end up calling drupal\_flush\_all\_caches in the end. You can play around with calling this in various circumstances in your own code.

# Answer
> 0 votes
We can use the following methods to clear the cache.

1. Visit /admin/config/development/performance and click on the *Clear cache* button
2. With Drush installed, run `drush cc all`
3. With database access, run the following SQL queries

```
TRUNCATE TABLE cache;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_token;
TRUNCATE TABLE cache_update;

```
4. From PHP code, with `db_query("DELETE FROM {cache}")`
5. From PHP code, calling `cache_clear_all()`

---
Tags: caching
---


# Question
Title: How do I programmatically check if a context is active?
How do I see which contexts are active on the page?

I can't find any `ContextManager` object in `hook_preprocess_page()`.

# Answer
> 3 votes
I figured it out: The Context module defines a service for getting the `ContextManager` object, which has `getActiveContexts()`. You can obtain it using the following code.

```
$activeContexts = \Drupal::service('context.manager')->getActiveContexts();

```

I need to read Service Container.

# Answer
> 2 votes
You can use this snippet in template\_preprocess\_page():

```
  // Pass vars to page.html.twig depending on active contexts
  $active_contexts = \Drupal::service('context.manager')->getActiveContexts();

  $vars['is_my_context_active'] = FALSE;
  foreach ($active_contexts as $context) {
    if ($context->getName() == 'my_context') {
      $vars['is_my_context_active'] = TRUE;
      break;
    }
  }

```

---
Tags: 8
---


# Question
Title: How to unit test hook_form_alter implementation code in custom module
How to unit test hook\_form\_alter implementation code in custom module?

# Answer
> 4 votes
Don't, that doesn't make sense. Unit tests make sense for APIs and classes, things with clear interfaces and definitions what's the input/output.

A form alter means you're altering more or less internal structures from another module that might change over time. Especially backend forms are explicitly excluded from Drupal Core BC for example, which means that they can be changed over time. You want to do a full browser test to make sure that your logic/changes actually work in the resulting form that is displayed in the browser.

See https://www.drupal.org/docs/8/testing/types-of-tests-in-drupal-8 for documentation of different types of tests in Drupal 8 and when they should be used. There are 4 different types of test classes for a reason.

---
Tags: 8, testing
---


# Question
Title: Control access to a custom blocks edit page
I have a small module which creates and adds some custom settings for a block. Now I would like to control access to this blocks edit page. All users should be able to display the block, while changing the actual the configuration only should be available to certain users. Since I am not able to use `hook_permission()` I am not really sure how to best solve this so any help would be much appreciated.

**Edit**

I have tried this without any success:

```
function MYMODULE_block_info() {
  return array(
    'MYBLOCK' => array(
    'info' => t('MYBLOCK'),
    'cache' => DRUPAL_CACHE_GLOBAL,
    ),
  );
}

```

When I clear the cache and tries to go to the blocks edit page the url changes but nothing happens. It is like I am still standing on the block overview page?

```
function MYMODULE_permission() {
  return array(
    'administer MYBLOCK' => array(
    'title' => t('Administer MYBLOCK'),
    'description' => t('Administer MYBLOCK settings.'),
   ),
  );
}

function MYMODULE_menu_alter(&$items) {
  $items['admin/structure/block/manage/MYMODULE/MYBLOCK/configure']['access arguments'] = array('administer MYBLOCK');
}

```

**Edit**

If I use `user_access()` in `hook_block_configure()` I almost achieve what I want. I don't know if this would be a valid way to solve this problem:

```
function MYMODULE_block_configure($delta = '') {
  $form = array();
  if ($delta == 'MYBLOCK') {
    if (!user_access('administer MYBLOCK')) {
      drupal_set_message(t('You are not allowed to edit the @block block.', array('@block' => $delta)), WATCHDOG_WARNING);
      drupal_goto('admin/structure/block/manage');
      drupal_exit();
    }
    // Setup form for the block here.
  }
  return $form;
}

```

# Answer
I was not able to solve this using `hook_menu_alter()`, instead I created a custom permission for my block and then used `user_access()` in the `hook_block_configure()` to check if the user has access or not:

```
function MYMODULE_permission() {
  return array(
    'administer MYBLOCK' => array(
      'title' => t('Administer MYBLOCK'),
    ),
  );
}

function MYMODULE_block_configure($delta = '') {
  $form = array();
  if ($delta == 'MYBLOCK') {
    // Check if user has permission to configure the block.
    if (!user_access('administer MYBLOCK')) {
      // In case the user does not have correct permission we
      // returns to the block overview screen and displays a warning
      // message.
      drupal_set_message(t('You are not allowed to edit the @block block.', array('@block' => $delta)), WATCHDOG_WARNING);
      drupal_goto('admin/structure/block/manage');
      drupal_exit();
    }
    // Setup form for the block here.
  }
  return $form;
}

```
> 0 votes

# Answer
```
/**
 * Implements hook_permission().
 */
function my_module_permission() {
  return [
    'my_module_custom_permission' => [
      'title' => t('My Module Custom Permission'),
      'description' => t('Explain what this permission allows the user to do.'),
    ],
  ];
}

/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items) {
  $items['admin/structure/block/manage/block/5/configure']['access arguments'] = ['my_module_custom_permission'];
}

```

If you use the code above, follow the steps below.

### Steps

1. Replace all instances of 'my\_module\_custom\_permission' to a machine name that makes sense.
2. Update the 'title' and 'description' for the custom permission.
3. Replace all instances of the word 'my\_module' with your module's machine name.
4. Change the `$items` path from what I have to the block path you are trying to update.

### Important to note

If the block you are editing was created from the frontend of the Drupal website, then it can be deleted. If it gets deleted and then recreated, the block's ID will change. Which in turn changes the path to the block's configuration page.

### Testing

Make sure to give your test user the permission we've just made and make sure they can edit the block configuration. Also, test a user who does not have the permission and make sure they can not edit the block configuration.
> 1 votes

---
Tags: 7, blocks, hooks, users
---


# Question
Title: How to set value programmatically for mobile number module's field using entity wrappers?
how do I set value for the mobile\_number field using entity wrappers? Currently, this field is attached to an entity and I'm trying as below.

$entity\_type = 'mp\_customer';
$entity = entity\_create($entity\_type, array('type' =\> 'mp\_customer')); $wrapper = entity\_metadata\_wrapper($entity\_type, $entity); $wrapper-\>field\_phone = "0777123456";

This gives an PDO Exception .... field\_phone\_value cannot be null....

Adding more This field needs more data to store in field\_data\_field\_phone, those are: {field\_phone\_value} {field\_phone\_country} {field\_phone\_local\_number} {field\_phone\_verified} {field\_phone\_tfa}

This field was created using this module : https://www.drupal.org/project/mobile\_number

# Answer
> 2 votes
To store a value with entity wrapper `set()` should be used. Please read https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers

So your code `$wrapper->field_phone = "0777123456";` would be `$wrapper->field_phone->set('0777123456');` if the field structure required just a simple string.

However, according to the error message, it is not a string as it requires additional values for `{field_phone_value} {field_phone_country} {field_phone_local_number} {field_phone_verified} {field_phone_tfa}`.

So to make sure I would first figure out its structure. You could do so, for example, saving any value via UI and then outputting the value of respecting variable using dpm(). However, most probably its an array and you could give a try to:

```
$phone = array(
  'field_phone_value' => '0777123456',
  'field_phone_country' => 'US',
  'field_phone_local_number' => 'some value',
  'field_phone_verified' => 'some value',
  'field_phone_tfa' => 'some value'
);
$wrapper->field_phone->set($phone);

```

---
Tags: entities
---


# Question
Title: How can I upload files with the form element type file?
I want to upload a file and I have to use form element type as 'file'. In submit function I am not able to get any proper data related to the file which I am uploading. SO Can anyone please help me to resolve this. Please find the below code:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['test_CERTIFICATE'] = [
    '#type' => 'file',
    '#title' => $this->t('Certificate'),
    '#description' => $this->t('Your Certificate (.pem file)').': '.\Drupal::state()->get('test_CERTIFICATE_NAME'),
  ];

  return parent::buildForm($form, $form_state);
}

```

Submit function:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);

  $validators = array('file_validate_extensions' => array('pem'));
  $files = file_save_upload('test_CERTIFICATE', $validators, 'public://certfiles', FILE_EXISTS_REPLACE);
  $file = File::load($files[0]);
  if ($file) {
    kint($files); exit;
    // here control is not coming
    $file->setPermanent();
    $file->save();
  }
}

```

# Answer
> 26 votes
I had the same problem with the `file` form element. Solved this by using `managed_file` and providing the upload location and validators in the form element:

```
$form['test_CERTIFICATE'] = [
  '#type' => 'managed_file',
  '#title' => $this->t('Certificate'),
  '#upload_location' => 'private://certfiles',
  '#upload_validators' => [
    'file_validate_extensions' => ['pem'],
  ],
];

```

Then in submit:

```
use Drupal\file\Entity\File;

$form_file = $form_state->getValue('test_CERTIFICATE', 0);
if (isset($form_file[0]) && !empty($form_file[0])) {
  $file = File::load($form_file[0]);
  $file->setPermanent();
  $file->save();
}

```

# Answer
> 16 votes
You can access files data uploaded through "file" field using the following code (from D8.5 core/modules/config/src/Form/ConfigImportForm.php)

```
$all_files = $this->getRequest()->files->get('files', []);
$file = $all_files['test_CERTIFICATE'];
$file_path = $file->getRealPath();

```

---
Tags: 8, forms
---


# Question
Title: Update problems when updating to Varbase
I updated a Drupal 8 site to Varbase release 16. After running update.php I get the following error.

> Symfony\Component\Routing\Exception\RouteNotFoundException: Route "content\_lock\_timeout.settings\_form" does not exist. in Drupal\Core\Routing\RouteProvider-\>getRouteByName() (line 190 of core\lib\Drupal\Core\Routing\RouteProvider.php).

Has anybody a idea how to proceed?

# Answer
The https://www.drupal.org/project/varbase/issues/2953417 shows Varbase is using Content locking module, which is causing the reported error. Try temporarily disabling it to proceed.
> 2 votes

---
Tags: 8, updating
---


title: User Content Posts

text:
# Question
Title: User Content Posts
Iam new in drupal. Now i build my first Content-Type for an Image Blog.

How to make these Content-Type available also for registred Users to submit their own Posts?

# Answer
> 1 votes
You just have to enable authenticated users to create that content (in permissions).

And make relevant links (`node/add/<content-type>`) available to them

# Answer
> 0 votes
Right now I'm assuming you haven't created any user roles beyond the default roles. IF that is the case then, assuming you are using D7 go to admin/people/permissions and find the permissions related to the content type you created. Set them to be able to be created by authorized user.

I believe D8 is a similar thing.

---
Tags: nodes, forms, users
---


# Question
Title: Display content referring other content in a mapping table
I have the following problem I can't figure out how to solve - note I am a Drupal newbie...

I have two content types; TypeA and TypeB. TypeA includes an entity reference field of TypeB to create a static relationship, similar to a "related work" or "is part of" use case.

This relationship displays fine in the full display mode for TypeA and all is well on that front.

I fail, however, to display this relationship as a mapping table in a third content type, where all TypeB nodes represents columns, and all TypeA nodes are displayed in individual rows like the following example:

**Example:**

Consider we have the following three nodes of TypeB: NodeA, NodeB, and NodeC.

We also have 5 nodes of TypeA, all along with the following relationships to TypeB nodes as follows:

* Node1 (NodeA, NodeC)
* Node2 (NodeA)
* Node3 (NodeB, NodeC)
* Node4 ()
* Node5 (NodeA, NodeB, NodeC)

The mapping table then would look like this:

```
      | NodeA | NodeB | NodeC
------|-------|-------|------
Node1 |   X   |       |   X
------|-------|-------|------
Node2 |   X   |       |
------|-------|-------|------
Node3 |       |   X   |   X
------|-------|-------|------
Node4 |       |       |
------|-------|-------|------
Node5 |   X   |   X   |   X

```

Obviously, I do not want to maintain this table manually, but be built depending on the actual dynamic content of the site.

**EDIT**

The following constraints also apply (forgot to mention them in the first place):

* When I unpublish or delete a node of content type TypeB, the entire column of this mapping table needs to disappear
* The view (anticipating that I can implement this through crafty Views configuration) should not be cached, or cache-cleared upon change (is that even possible?)
* The "X" in the example table would ideally be replaceable with other code or content I control (e.g. a little image, or glyph or so)

Thanks a lot,

Michel

# Answer
I don't think you can build that with views or another UI tool just by clicking it together.

It should however not be too complicated to build with a but of custom code.

You need to build an entity query that gets all TypeA nodes, another one that gets all TypeB nodes, loop over Type, and for the columns, loop over the Type B and check if you have a reference for them in your field.

IMHO writing out the full code is too much for a single question, I suggest you get started and if you have problems, ask specific questions.

Obviously that table will get huge if you have a lot of nodes of either type or even both.
> 0 votes

---
Tags: views, 8, entities
---


# Question
Title: Difference between create new and edit node in form alter
I have an alter section for a particular content type. In the form alter how can I find out whether it is **create new form** or **edit form**?

With dsm($form) in from alter I can get results with several differences between them. What is the best way to distinguish those from each other?

is this a good way?

```
    if(isset($form['nid']['#value']))
     'means in edit form'
    else
     'means in create new from'

```

# Answer
> 70 votes
If you look at the code of node\_object\_prepare(), which is called from node\_form() (the form builder for the node edit/create form), you will see it contains the following code.

```
  // If this is a new node, fill in the default values.
  if (!isset($node->nid) || isset($node->is_new)) {
    foreach (array('status', 'promote', 'sticky') as $key) {
      // Multistep node forms might have filled in something already.
      if (!isset($node->$key)) {
        $node->$key = (int) in_array($key, $node_options);
      }
    }
    global $user;
    $node->uid = $user->uid;
    $node->created = REQUEST_TIME;
  }

```

In an implementation of `hook_form_BASE_FORM_ID_alter()`, it is enough to use code similar to the following one.

```
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];

  if (!isset($node->nid) || isset($node->is_new)) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}

```

If the node is new, then the form is creating a node; if the node is not new, then the form is editing an existing node.

In Drupal 8, every class implementing `EntityInterface` (including the `Node` class) override the `EntityInterface::isNew()` method. Checking if a node is new becomes as easy as calling `$node->isNew()`. Since in Drupal 8 there isn't `$form_state['node']` anymore, the code becomes the following.

```
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state->getFormObject()->getEntity();

  if ($node->isNew()) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}

```

# Answer
> 12 votes
Yes, you have to check if the node ID exists or not.

# Answer
> 4 votes
```
/**
 * Implementation of hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form['#node'] && $form['#node']->type .'_node_form' === $form_id) {
    // Is node form.

    if ($form['#node']->nid) {
      // Is node edit form.
    }
  }
}

```

# Answer
> 2 votes
In **Drupal 8** you will need the `form_id` variable and it will be different on each case and it will include the `_edit_` in it if we are editing a node

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == '"node_article_edit_form"'){
        //edit form
    }
    if($form_id == 'node_article_form') {
        //create form
    }
}

```

---
Tags: forms
---


# Question
Title: Why can't I delete both account and content when cancelling a user account, in Drupal 8?
Before, drupal 7 core, and in drupal 6, a contrib module called user\_delete, had this 4th option in deleting user accounts settings:

"Delete the account and its content." (drupal 7) and

"delete a user and delete all submitted content including nodes and comments" (drupal 6)

But this option seems unavailable in drupal 8 core. Why?

I really want both account and content deleted. The option they offer would force me to periodically delete the unpublished content of the removed account via cron.

Or am I missing something here?

# Answer
> 0 votes
Deleting content requires an access check, and as such the *Delete the account and its content.* option can't be selected as the default. I presume this is because a user can have access to cancel their own account, but not be able to select the method, and there's no mechanism implemented to provide a fallback for the default.

You'll still see it when cancelling an individual account, provided you have the *administer users* permission:

If you'd rather get control of that process yourself you can implement `hook_user_cancel_methods_alter` to remove or change the access check.

---
Tags: 8, nodes
---


# Question
Title: Views UI doesn't provide links to expand fieldsets anymore
I have moved an entire drupal site to another server. While everything else seems to work fine, I can't quite access collapsed fieldsets in Views UI anymore. It looks like this

All fieldsets (STYLE SETTINGS and so forth) are collapsed. The fieldset label however is not a link. The content of the fieldset exists when I view the HTML of the site. If I remove the CSS

```
html.js fieldset.collapsed .fieldset-wrapper {
  display: none;
}

```

I can again see the fieldsets' contents, but the error must be somewhere else. But I don't have any clue where to look for. Anyone has an idea?

I tried to google the error, but it seems all known errors are related to some "Expand all" or "Collapse all" buttons.

# Answer
> 0 votes
This probably means that there is something wrong with JS making collapsible not work.

Is there anything in the JS error log? Check if all JS files are moved and that they are complete. Also check for error 404 for JS files.

# Answer
> 0 votes
usually this is a js error that comes when you install jquery\_update

go to jquery\_update settings and make the jquery for admin less than version 1.10 probably 1.7 will work

make sure you clear cache

# Answer
> 0 votes
Navigate to /admin/config/development/performance. Clear the caches. If any of the JS files are aggregated and/or minified, clear those caches as well.

---
Tags: 7, views, javascript
---


# Question
Title: Suggested theme hook doesn't get applied
The custom theme hook (abacus-product.html.twig) I've appended via a hook function doesn't get applied. But it shows up in the suggestions.

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   * abacus-product.html.twig
   * page--taxonomy--term--5.html.twig
   x page--taxonomy--term--%.html.twig
   * page--taxonomy--term.html.twig
   * page--taxonomy.html.twig
   * page.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/abacus/templates/page--taxonomy--term--%.html.twig' -->

```

abacus-product.html.twig is in the same directory as page--taxonomy--term--%.html.twig

**Edit** This is the hook function:

```
function abacus_theme_suggestions_page_alter(array &$suggestions, array $variables) {
    $path = \Drupal::service('path.current')->getPath();
    if (0 === strpos($path, '/taxonomy/term/')) {
        $weight = \Drupal::routeMatch()->getParameter('taxonomy_term')->getWeight();
        if ($weight == 0) {
            $suggestions[] = 'abacus-product';
        }
    }
}

```

# Answer
**EDIT**, after further debugging (see comments):

Using `$suggestions[] = 'page__abacus__product'` and a template called `page--abacus--product.html.twig` works. Theme suggestions should contain double underscores.
> 4 votes

# Answer
I think that the $suggestions\[\] = 'abacus-product'; is the problem for two reasons.

First it needs to start with the theme hook with two underscores - i.e. page\__abacus-product.

And - this is a subtle error - the '-' in abacus-product should be an underscore. So the line should be: $suggestions\[\] = 'page\__abacus\_product';

I know that the template will use a hyphen - and the suggestions listed by debug will have hyphens - but unless it is an underscore first the template file will not be used.

Also - not putting page\__ at the beginning may result in the wrong twig template variables not being consistent with the variables in the base template.
> 2 votes

# Answer
To get the abacus-product.html.twig template picked up you need to register it with a hook\_theme() implementation first. Unfortunately in this case the theme debug is a bit misleading for you, but the theme debug functionality is not tied into the theme registry so it can't know whether you've registered `abacus_product` or not.

Example code:

```
/**
 * Implements hook_theme().
 */
function abacus_theme() {
  return array(
    'abacus_product' => array(
      'base hook' => 'page',
      'render element' => 'page',
    ),
  );
}

```

However that approach might be a bit unusual depending on your use case. If you're happy with the 'page' prefix, you can just "extend" the `page` theme hook with a suggestion like so (it doesn't need to contain 3 parts as eluded to in the comments):

```
$suggestions[] = 'page__abacus_product';

```

That would allow you to use a template `page--abacus-product.html.twig` without needing to implement `hook_theme()` at all. drupal\_find\_theme\_templates() automatically adds templates that are extending existing hooks (suffixed with double underscore) to the theme registry. This means that such templates don't need to be registered separately in a `hook_theme()`, like the above `page--abacus-product.html.twig`, because `page` already exists in the theme registry.

This code in `\Drupal\Core\Theme\ThemeManager::theme()` (right after the suggestion alter hooks are invoked) is where the theme registry is checked.

```
// Check if each suggestion exists in the theme registry, and if so,
// use it instead of the hook that _theme() was called with. For example, a
// function may call _theme('node', ...), but a module can add
// 'node__article' as a suggestion via hook_theme_suggestions_HOOK_alter(),
// enabling a theme to have an alternate template file for article nodes.
foreach (array_reverse($suggestions) as $suggestion) {
  if ($theme_registry->has($suggestion)) {
    $info = $theme_registry->get($suggestion);
    break;
  }
}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to transfer field location inside a div?
I am looking for a way to transfer the location of the field created programmatically inside a div created by field\_group module.

Can anyone help me to achieve this?

Thank you.

# Answer
I was able to achieve this using javascript:

```
<script>
$("#edit-field-date").appendTo("#detail-wrap");
</script>

```

But I am still looking for a way to do it under form\_alter.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Custom Password validation on Drupal 7 form
I am using the Drupal Form API for a customized Login System. It has the password field which needs to be validated. We have a custom criteria of Uppercase, Lowercase, numeric and special characters to validate the password.

The one way I see is to write the RegEx inside the Validate function. Is there an alternate way in Drupal to do this via an existing function or module?

(I am aware that the Webform Validation Module can do this for the webforms.)

Thanks.

# Answer
> 2 votes
Please check Password Policy module. It will satisfy all your above requirements (Uppercase, Lowercase, numeric and special characters).

# Answer
> 0 votes
If you want to use password field in custom form do not have to use any custom modules use drupal password settings.

Just add type as '**password\_confirm**' in your form.

This automatically add confirm password field and match all the password standards of drupal.

```
 $form['pass'] = array(
    '#type' => 'password_confirm',
    '#size' => 25,
    '#description' => t('Enter the new password in both fields.'),
 );

```

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


title: How can I change form action link?

text:
# Question
Title: How can I change form action link?
How can I change form action in drupal 8?

In default, page not change and when my form path is `/site/drupal/page`, my form action is `<form data-drupal-selector="test" action="/site/drupal/page" method="post" id="test" accept-charset="UTF-8">`.

But I want change it to other page. How can I do this ?

\** Redirect not worked, see this link: Redirect after submit form

# Answer
> 4 votes
In the form submit handler, you can modify the $form\['action'\] value.

```
// Get the routename
$routename = 'My-Route';
  $url = \Drupal\Core\Url::fromRoute($routename);
  // make the redirection
  $form['#action'] = $url->toString();

```

# Answer
> 1 votes
in the submit form write a redirect

```
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

//add the below in submit form handler. Use the route name you want to redirect
$response = new RedirectResponse(Url::fromRoute('<front>')->toString());

$response->send();

```

---
Tags: 8, forms
---


# Question
Title: Is it possible to implement theme preprocessor on specific template in drupal 8?
What I am here trying to achieve is simple. I want to change the default drupal "submitted by" field to only render day and date but not the time when the node was created. To do so I want to preprocess the field which is being evoked by field.html.twig. But apparently, I don't want to run the preprocess on every field by using hook suggestion "field". Hence i created the specific template "field--default--node--node-submitted-by--blogs.html.twig". Now I want to implement theme preprocessor on this specific template. Can achieve on based on template suggestions or not?If so how?

# Answer
> 0 votes
If you implemented your own template suggestion then it's as easy as writing a function with the following name:

```
function THEME_OR_MODULE_NAME_preprocess_field__default__node__node_submitted_by__blogs(&$variables) {
}

```

The main thing to take care of is to convert the hyphen characters (-) to underscores (\_).

Good luck!

---
Tags: theming, hooks
---


title: Tell a field to be translatable

text:
# Question
Title: Tell a field to be translatable
I have a module with a plugin block. In the blockForm I create all the fields that I need for this block. In the CMS I realized that only the title of my block is translatable. I need some of my custom fields to be translatable. I just can't find how to do that.

```
public function blockForm($form, FormStateInterface $form_state){

    [...]

    $form['exit_link']['full_schedule_link'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Full Schedule Link'),
      '#description' => $this->t('Enter the schedule node, ex: (/node/20)'),
      '#default_value' => isset($this->configuration['full_schedule_link'])?    $this->configuration['full_schedule_link']:'',
      '#maxlength' => 256,
      '#size' => 64,
      '#weight' => '1',
      '#translatable' => true // <-- NOT WORKING
    );

    [...]

}

```

Anyone has an idea how to do this?

# Answer
You define that through the config schema, not the form.

See https://www.drupal.org/node/1905070, use type: label (weird know but that's how it is called) not string and type: text for textareas.

If you have no config schema yet, look at other modules providing blocks with configuration, like aggregator.module to see how to define that.
> 4 votes

# Answer
Following the Aggregator module as an example, I implemented the following code to alter the translation form and add the WYSIWYG text format.

```
    function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (($form_id == 'config_translation_edit_form' || $form_id == 'config_translation_add_form') && isset($form['config_names']['block.block.block_id']['settings']['field_name']['translation'])) {
    if (is_array($form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value'])) {
      $default_value = isset($form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value']['value']) ?
        $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value']['value'] : '';
      $default_format = isset($form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value']['format']) ?
        $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value']['format'] : 'rich_text';
      $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value'] = $default_value;
      $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#format'] = $default_format;
      $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#type'] = 'text_format';
    }
    else {
      $default_value = isset($form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value']) ?
        $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value'] : '';
      $default_format = 'rich_text';
      $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#default_value'] = $default_value;
      $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#format'] = $default_format;
      $form['config_names']['block.block.block_id']['settings']['field_name']['translation']['#type'] = 'text_format';
    }
  }
// here reverse the order of the submit handlers, so that the we can manage the values before the default submit
  $form['#submit'][0] = 'mymodule_form_submit';
  $form['#submit'][1] = '::submitForm';
}

function mymodule_form_submit(&$form, FormStateInterface $form_state) {
  $field_name= $form_state->getValue('translation')['config_names']['block.block.block_id']['settings']['field_name']['value'];
  // this is the label of the block
  $label = $form_state->getValue('translation')['config_names']['block.block.block_id']['settings']['label'];
  $translation['config_names']['block.block.block_id']['settings'] = [
    'label' => $label,
    'field_name' => $field_name,
  ];

    $form_state->setValue('translation', $translation);
}

```

After altering the form, it won't submit right, and the values wouldn't display for the second language. I had to add a submit handler in order to send the right arrays to the default submit. Not sure if this is the best way, but it is working right.

I thought that this may be helpful for those users who run into this issue.
> 0 votes

---
Tags: 8, forms, blocks, i18n-l10n
---


title: Generate an internal URL in twig

text:
# Question
Title: Generate an internal URL in twig
I want to generate an internal URL in my twig template Here is my code but it's not working

```
{% if(is_admin) %}
                    <li class="edit-sidebar-menu">
                        <a href="{{ url('admin/structure/menu/manage/fixed-sidebar-menu') }}">Edit Menu</a>
                    </li>
{% endif%}

```

# Answer
> 3 votes
To generate an internal url in Twig you can follow these steps:

1. Install the module Devel.
2. Go to **Routes Info** (/devel/routes) and search in the browser for the path :

3. Add the route name and the route parameter to `url()`:

`<a href="{{ url('entity.menu.edit_form', {'menu': 'fixed-sidebar-menu'}) }}">Edit Menu</a>`

# Answer
> 2 votes
If you have installed drupal console. Use the below command to list all routes in the site

```
drupal debug:router

```

Route name for admin/structure/menu/manage/{menu} is

```
entity.menu.edit_form

```

So twig code should look like

```
<a href="{{ url('entity.menu.edit_form',{'menu':'fixed-sidebar-menu'}) }}">Edit Menu</a>

```

# Answer
> 0 votes
please try like this:

```
<a href="{{ url('contact.my_page') }}">{{ 'Contact'|t }}</a>

```

for more details look at this link: https://www.drupal.org/node/2486991#path

---
Tags: 8, theming
---


# Question
Title: Accessing Additional User Profile Fields
I added a dozen or so new fields (in Drupal 7) to the user profiles using:

Configuration -\> People -\> Account Settings -\> Manage Fields (admin/config/people/accounts/fields)

How can I access these values? They do not seem to be part of $user

Tried, without success:

```
global $user;
var_dump($user);

```

# Answer
I think I found it. There is one additional step it seems.

```
global $user;
$user_full = user_load($user->uid); // user_load(uid) returns the complete array
var_dump($user_full);

```

I now have access to my custom profile fields through $user\_full
> 13 votes

# Answer
Panels can also do this quite painlessly with relationships.
> 1 votes

# Answer
For some weird reason, the profile fields in Drupal 7 are not what they used to be. However, the user profile object makes the additional profile fields accessible as array elements. For example:

```
$profile->field_fieldname['und'][0]['value']

```

is not available but it will work when rewritten like this:

```
$user_profile['field_fieldname']['#object']->field_fieldname['und'][0]['value'];

```

So I simply did the following in my code:

```
/*
 * Create simplified variables as shortcuts for all fields.
 * Use these variables for read access lateron.
 */
$firstname = $user_profile['field_first_name']['#object']
  ->field_first_name['und'][0]['value'];

$middlename = $user_profile['field_middle_name']['#object']
  ->field_middle_name['und'][0]['value'];

$surname = $user_profile['field_surname']['#object']
  ->field_surname['und'][0]['value'];

$image = $user_profile['field_user_picture']['#object']
  ->field_user_picture['und'][0]['uri'];

```

Just another way of getting things working, instead of calling the `$user` object yet again.
> 0 votes

# Answer
I'm reposting my answer from https://stackoverflow.com/questions/8124089/get-value-of-custom-user-field-in-drupal-7-template here since I think this is an alternative solution. This example shows how to use something like field\_real\_name instead of the default username.

If you are using a preprocess function, there is no need to pull in the global `$user` object. You can change the field in the $variables array that is `$variables['name']` to what you have in your custom field that I've called `field_real_name`. You have access to the `$variables` array, so you can get the user information with this - it will load the information associated with the uid (see template\_preprocess\_username):

```
function mythemename_preprocess_username(&$variables) {
    $account = user_load($variables['account']->uid);
    ...more code will go here in a moment
}

```

If you `dpm($account)` (or `kpr($account)` if you aren't using devel) you will see that you have access to all of the user information, without using the global `$user` object.

Then you can change the output of `$variables['name']` to be your `field_real_name` as follows:

```
function mythemename_preprocess_username(&$variables) {

  // Load user information with user fields
  $account = user_load($variables['account']->uid);

  // See if user has real_name set, if so use that as the name instead
  $real_name = $account->field_real_name[LANGUAGE_NONE][0]['safe_value'];
  if (isset($real_name)) {
    $variables['name'] = $real_name;
  }
}

```
> 0 votes

# Answer
You can load user data (custom fields included) with Drupal 7 core

```
$user = entity_load($entity_type = "user", $ids = Array($user->uid), $conditions = array(), $reset = FALSE);

```

More details at Drupal 7 \> API \> Entity load
> 0 votes

---
Tags: 7, users
---


# Question
Title: How can I remove only submitted time from node view?
I only need to remove the published time from the submitted by field while viewing the node. Is it possible to do with display suite or there are other different approaches?

# Answer
**Step 1**-\>create a custom date format go to **"admin/config/regional/date-time"** then click **"Add format"** link,give appropriate name, in my case i have taken name **"new custom"**, in format string input **"l,F d, Y"** then save.

**Step 2**-\>In your Your\_theme.theme file write the preprocess function for node:

```
function Your_theme_preprocess_node(&$variables) {
// Getting the node creation time stamp from the node object.
  $date = $variables['node']->getCreatedTime();
// Here you can use drupal's format_date() function, or some custom PHP date formatting.
 $variables['date_custom'] = \Drupal::service('date.formatter')-
 >format($date, 'Machine_name_of_created_date_format'); //In my case machine name was "new_custom"
   }

```

**Step 3**-\>Create a twig template of your content type like **node--your-content-machine-name.html.twig**

replace the following line : {% trans %}Submitted by {{ author\_name }} on {{ date }}{% endtrans %}

with

{% trans %}Submitted by {{ author\_name }} on {{ date\_custom }}{% endtrans %}
> 0 votes

# Answer
for D7, not shure for D8, in your template.php file inside your theme, replace YOURTHEME with your sub-theme name, place this funcion:

```
/*
*  change "submited by"
*/
function YOURTHEME_preprocess_node(&$vars) {
  $vars['submitted'] =
  t('!username ',
    array('!username' => $vars['name']));

  $vars['date'] =
  t('!datetime',
    array('!datetime' => format_date($vars['node']->created,
        'custom', 'M/d/Y')));
  }

```

for a diferent date format see: http://php.net/manual/es/function.date.php
> 0 votes

---
Tags: display-suite
---


# Question
Title: Programmatically create a node with a menu link
I created a node programmatically with the following code.

```
$data = array(
  'type' => 'inception_article',
  'title' => $msg->name,
  'body' => array(
    'value' => $msg->body,
    'format' => 'full_html'
  )
);

$node = Node::create($data);
$node->save();

```

I would now also like to create the menu link for the node, but I cannot figure out how to do that in Drupal 8.

How can I programmatically create a menu link for a node I create?

# Answer
You can save menu link Separately using the below code on node save.

```
 $menu_link = MenuLinkContent::create(array(
      'title' => 'Menu Title', // Menu title is your title of menu, in this case node title
      'path' => '/path/to/node', // Menu link something like '/node/'.$nid, replace $nid with your node id
      'menu_name' => 'navigation',
      'weight' => 0,
      'bundle' => 'menu_link_content',
 ));

 $menu_link->save();

```
> 1 votes

# Answer
To have the menu also on the node entity, you need to pass the link uri as entity:

```
MenuLinkContent::create([
  'title' => 'Menu title', // Menu title is your title of menu, in this case node title
  'link' => ['uri' => 'entity:node/' . $node->id()],
  'menu_name' => 'main',
  'weight' => 0,
])->save();

```
> 1 votes

---
Tags: nodes, 8
---


# Question
Title: Attach behavior only to the file upload button
I have a form with a managed\_file field where I need to know when the upload button is clicked, and then perform an action. I decide to make it by attaching a behavior to my button but it also trigger when I click on the remove button. Here is my code:

```
Drupal.behaviors.mattButtons = {
    attach: function (context) {
    jQuery('input.form-submit', context).bind('mousedown', Drupal.matt.checkFile );
    }
};

Drupal.matt = Drupal.matt || {
    checkFile : function(){
        console.log("Hello");
        var url = jQuery('.file a').attr('href');
        console.log(url);
    }
};

```

Is there any way to only attch my behvior on the file upload button?

# Answer
> 0 votes
You can simply be more specific with your jQuery selector. For example, you could theme\_file\_managed\_file to give your upload button it's own class and then change your jQuery('input.form-submit', context) line to include that class in the selector.

```
jQuery('input.my-upload-class', context)

```

---
Tags: 7, forms, javascript
---


# Question
Title: Replicating a Node with Replicate UI Leads to an Incorrect Hreflang Tag
we are using the Replicate UI module to replicate nodes and then changing the new replicates language to build up our site in different languages.

However, we are seeing an issue with our Hreflang tags where the hreflang tag gets the correct url of the new node, but keeps the old language code.

So let's say the old node was in English and the new one is in German - the hreflang tag still says that the new version hreflang that still contains "en" rather than "de" like that:

```
<link href="https://de.website.com" rel="alternate" hreflang="en" />

```

The question is, how can we change the hreflang code once the page is replicated? We have multiple pages that we do not want to create from scratch.

# Answer
As the module's page on https://www.drupal.org/project/hreflang says if it's for Drupal 8, then you should implement hook\_language\_switch\_links\_alter() or hook\_page\_attachments\_alter() to modify the hreflang tags. If it's for Drupal 7 then use either hook\_language\_switch\_links\_alter() or hook\_html\_head\_alter()
> 0 votes

---
Tags: i18n-l10n
---


title: Double field module theming

text:
# Question
Title: Double field module theming
Could anyone please help with the Double field module in Drupal 8 and Twig? I am trying to produce the following with no luck so far as I cannot figure out the proper Twig variables to use.

```
<li><dl class="classname"><dt>{{ first }}</dt><dd>{{ second }}</dd></dl></li>

```

I would like to have the raw values in the html above. -- I'm adding some more info here because my goal is to understand the mechanics of twig in this case and how I can get the field values of the two subitems

I have overriden (as suggested by drupal's theme debug system) the field--fieldname.html.twig template in which I have the following

```
<ul class="list-sm">
{% for item in items %}
<li>
  <dl class="list-terms-inline">
    <dt>
      {{ item.first }}
    </dt>
    <dd>
      {{ item.second }}
    </dd>
  </dl>
</li>
{% endfor %}
</ul>

```

which is not printing anything in the value areas and apart from that does not iterate through all the items either.

# Answer
> 0 votes
If you are using default (Unformatted list) formatter override *double-field-item.html.twig* template with the following markup:

```
<dt>{{ item.first }}</dt><dd>{{ item.second }}</dd>

```

Note that Double field ships with HTML list formatter which may render definition list so you might not need to override anything.

---
Tags: 8, theming
---


title: More filter options on admin/content

text:
# Question
Title: More filter options on admin/content
Is there a way to have more/advanced filters on `https://example.com/admin/content` using Drupal 8? Like filtering for taxonomy terms or fields for example?

# Answer
> 11 votes
Yes. Now that Views is integrated into Drupal 8, the `admin/content` display can be driven by a customizable View.

Make sure the **Views**/**Views UI** module is enabled in `admin/modules`, then navigate to `admin/structure/views`. You'll see a View named **Content** which corresponds with `admin/content`. You can edit that view to add various exposed filters that correspond with your own content setup (e.g. custom taxonomy filtering).

---
Tags: views, 8
---


title: Simple form builder

text:
# Question
Title: Simple form builder
I want to allow website managers(editors) to build custom forms:

* Editors should be able to create a form with a few text fields and specify the recipient emails.
* Form should send email with fields content
* The forms should be simply managed
* The forms submissions should be stored and listed in backend.

Currently there are few options, but none of them can be used by website managers. See the reasons below:

Contact module (core):

1. I do not want to allow editors to manage entity fields, it is overhead.
2. The module exports forms as a configuration.

Webform

1. The UI is too complex for editors. There are a lot of available fields, some pages and settings like access, ajax usage and additional logic.
2. The module exports forms as a configuration.

Eform (Entity form) is unsupported.

Currently we trying to do it with webform. We are trying to hide the unnecessary settings with form alter :-D Also we are trying to avoid webforms configuration export/import.

How do you create form builders for website managers(editors)?

# Answer
> 4 votes
I am the guy that created the complex Webform UI. For my clients, I disable any unneeded elements, handlers, and exporters. I also use hook\_form\_alter() to hide (via #access: FALSE) any feature that is not needed. I also have people create forms from Templates which have form behaviors and email handling preconfigured. You can also use hook\_webform\_create() to define reasonable defaults.

People are using the Config Split module to manage webforms (and blocks) configuration.

BTW, one day I hope someone will sponsor a Webform sub-module that allows site administrators to pick and choose which Webform features and element properties should be available to site builders.

---
Tags: 8, forms, webforms, emails
---


title: Synchronize with only published nodes

text:
# Question
Title: Synchronize with only published nodes
We are going to have a "staging" server where all edits will be made. We are going to push to the cloud production server with Drush sync. I know there is a way to exclude tables, but is there a way to only push nodes and field data from published nodes/revisions?

# Answer
> 1 votes
Viewing all the options listed on https://drushcommands.com/drush-8x/sql/sql-sync for `drush sql-sync` command, it seems you can apply limitations on a table level only. So you might want to build a custom code for syncing data as there is no way to push nodes and field data using Drush sync per their published statuses.

---
Tags: drush
---


# Question
Title: How to use user_external_login_register() with user authenticated by token?
So, I'm working on an Oauth2 implementation, and I'm forced to use a custom module as the existing modules all have slightly differing functionalities than my use case, assume Drupal-to-Drupal implementation, or request the user credentials to be submitted to the remote server (which is not how Oauth should be implemented).

Using the standard authflow, the users are redirected and authenticate against a remote server, and are returned with an access code which is then submitted for an auth token, which is finally used to get user info from the remote API. Finally, I take the json response, format it into an array to be created into an user object, and this is where I'm stuck.

The examples presented on the User External Login Register API page seem to assume querying an external database to check for the user's existence. In my case, I have the user info and name, and need to create a user and log them in with that information. This is my current attempt which doesn't seem to be working. I modified the API example use the user\_load\_by\_name() function to see if the user exists. Otherwise, I'm not sure how I should approach this otherwise.

So, my question is: 1) How do I correctly use this function? the example uses it without a module prefix, but if I declare it as a regular function I get a fatal error about re-declaring functions.

```
  $cs_user = array(
        'name' => $user_info['data']['user']['lastname'] . "_psr",
        'mail' => $user_info['data']['user']['email'],
        'pass' => $user_info['data']['user']['lastname'] . "_user_pass",
        'init' => $user_info['data']['user']['lastname'] . "_psr",
        'signature_format' => 'full_html',
        'status' => 1,
        'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user',
                            22 => 'CS User External',),
        'field_first_name' => array(array('value' => $user_info['data']['user']['firstname'])),
        'field_last_name' => array(array('value' => $user_info['data']['user']['lastname'])),
        'field_chapter' => array(array('value' => $user_info['data']['user']['groups']['0']['title'])),
       );
    //format the user info, feed it to external_user_login_register
    $name = $cs_user['name'];
    $module = 'chapterspot_signon';
    echo "<hr>";
    }
    function chapterspot_signon_user_external_login_register($name, $module){
        $account = user_load_by_name($name);
$account = $name;
        if (!$account) {
        // Register this new user.
        $account = user_save(drupal_anonymous_user(), $cs_user);
        // Terminate if an error occurred during user_save().
        if (!$account) {
          drupal_set_message(t("Error saving user account."), 'error');
          return;
        }
        user_set_authmaps($account, array(
          "authname_{$module}" => $name,
        ));
      }
      // Log user in.
      $form_state['uid'] = $account->uid;
      user_login_submit(array(), $form_state);
      drupal_goto('/members');
    }

```

Update: The issue here is how to instantiate the function? The API page shows the function being called without a module prefix. When I run the code as `user_external_login_register()` I get a fatal error. When I try to run the function as `mymodule_user_external_login_register` nothing happens e.g.

```
$name = $cs_user['name'];
$module = 'chapterspot_signon';
function chapterspot_signon_user_external_login_register($name, $module){
echo "This is working";
}

```

Update 2: Apparently, the code within the function works by itself.

# Answer
Not sure if this fixes the situation for you, but you can run the code inside the function without the wrapper. As you point out, the external server is handling the authentication for you, so there's no reason to pass the details through the user module validation functions. You will still need to do any user maintenance in your module, but this code will log a user in and pass them to the page you want.

```
  $account = user_load_by_name($name);
  if (!$account) {
  // Register this new user.
  $account = user_save(drupal_anonymous_user(), $cs_user);
  // Terminate if an error occurred during user_save().
  if (!$account) {
  drupal_set_message(t("Error saving user account."), 'error');
  return;
  }
  user_set_authmaps($account, array(
  "authname_{$module}" => $name,
  ));
  }
      // Log user in.
      $form_state['uid'] = $account->uid;
      user_login_submit(array(), $form_state);
      drupal_goto('/members');

```
> 0 votes

# Answer
It seems a couple of mistakes in your above code.

Your **$cs\_user** array below line should be populated with **name** instead of **lastname**

```
'name' => $user_info['data']['user']['lastname'] . "_psr",

```

Also, It seems 2nd line of your function **function chapterspot\_signon\_user\_external\_login\_register($name, $module)** is not needed. Because if you **Initialize** your **$account** variable with **$name** then your condition **if (!$account) {** never comes true and the code written into that if condition will never executed.

You can try two approaches it will work for you:

1) Call Built-in function **user\_external\_login\_register($name, $module)** from your custom module.

**Example:**

```
user_external_login_register("addweb-solution", "your-custom-module-name");
drupal_goto('/members');

```

2) You can write your own function as below in your custom module:

```
function test_user_external_login_register($name, $module){
        $account = user_load_by_name($name);
        // $account = $name;
        if (!$account) {
            $userinfo = array('name' => $name,
              'pass' => user_password(),
              'init' => $name,
              'status' => 1,
              'access' => REQUEST_TIME,
            );
            // Register this new user.
            $account = user_save(drupal_anonymous_user(), $userinfo);
            // Terminate if an error occurred during user_save().
            if (!$account) {
              drupal_set_message(t("Error saving user account."), 'error');
              return;
            }
            user_set_authmaps($account, array(
              "authname_{$module}" => $name,
            ));
        }
        // Log user in.
        $form_state['uid'] = $account->uid;
        user_login_submit(array(), $form_state);
        drupal_goto('/members');

}

```

Hope this will helps you.

Thanks!
> 0 votes

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


# Question
Title: Show node's content moderation state in a view
How can I display the current moderation state for the node in a view and filter on it?

# Answer
In Drupal 8.5 this has gotten a lot easier.

Pre-requesities:

1) Enable content\_moderation (which enables workflows).

2) Set up a workflow with content moderation states.

3) Create a new view with the base table "Content Revisions". This is important, as the main content out of the box is based on "Content" which refers to the default revision. We want to see the latest revision. I made this mistake at first where I took the default content view and added a relationship to Content: Moderation State. This is the moderation state of the default revision, which is not what we want to see. We want to see the moderation state of the latest revision.

4a) Under "Filter Criteria" add filter "Is Latest Revision".

5) To display the moderation state, under "Fields" select "Content Revision: Moderation state".

6) To filter by moderation state, under "Filter Criteria" add filter "Content Revision: Moderation state" and expose it.

7) Save your view.

8) You'll need to update your content so that it has moderation states. This can be done by resaving it.

For example you could run:

```
  $article_nids = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->execute();

  $articles = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($article_nids);
  foreach ($articles as $article) {
    $article->save();
  }

```

Now your view should show moderation states.

It looks like Drupal 8.5 also adds a subtask on the system.admin\_content route that shows a link to a page that displays moderated content.

If you'd like to turn off these subtasks:

```
/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  if ($route_name == 'system.admin_content') {
    if (!empty($data['tabs'][1]['content_moderation.content'])) {
      unset($data['tabs'][1]['content_moderation.content']);
    }
    if (!empty($data['tabs'][1]['content_moderation.moderated_content'])) {
      unset($data['tabs'][1]['content_moderation.moderated_content']);
    }
  }
}

```
> 5 votes

---
Tags: views, 8
---


# Question
Title: REST post plugin broken from Drupal 8.4.5 to 8.5
I just upgraded my Drupal installation from 8.4.5 to 8.5 Now my REST plugin is not getting any data on POST.

My client post like this:

```
POST /rgptemprest?_format=hal_json HTTP/1.1
Host: 10.10.10.1:443
Authorization: Basic ****REPLACED******
Content-Type: application/hal+json
Accept: application/hal+json
User-Agent: ESP8266
Connection: close
Content-Length: 108

{"netcard":"997800940160","DS18B20":"28ADBCE70800008C","battery":"2952","temperature":"23.375","rssi":"-33"}

```

On my drupal server I have a plugin with this code (not complete)

```
public function post(array $data = [])
{
    var_dump($data);
    if (!empty($data))
    {

```

....

And here I see the difference on 8.4.5 it show an array of the data sent:

```
array(5) {
  ["netcard"]=>
  string(12) "997800940160"
  ["DS18B20"]=>
  string(16) "28ADBCE70800008C"
  ["battery"]=>
  string(4) "2952"
  ["temperature"]=>
  string(6) "23.500"
  ["rssi"]=>
  string(3) "-33"
}

```

but on 8.5 it's empty

```
array(0) {
}

```

What has changed between 8.4.5 and 8.5? And what do I need to change?

# Answer
> 2 votes
Wim Leers found the answer:

Change this:

```
public function post(array $data = [])

```

to:

```
public function post(array $data)

```

---
Tags: 8
---


# Question
Title: Show Webform Confirmation message in popup window
In my drupal7 site i have buit a contact form using Webform.

I like to do two things.

1. I want to show webform confirmation message in popup window.I have searched net found some popup module but the problem is they all belongs to drupal 6
2. When i submit the webform i am getting this error message

> Notice: Undefined index: #webform\_component in theme\_webform\_display\_select() (line 522 of /var/www/www.example.com/www/example/sites/all/modules/webform/components/select.inc).

Can you help me to solve this two things.Thank you friends

# Answer
Without doing any coding to achieve this you could use a module like Purr Messages and then adjust the style of it's output with CSS, this would apply to all system messages though..

Otherwise like zerocoolhotone mentioned, the simple dialog is an effective way of achieving this too.

Regarding your second question, it's a bug/issue with webform, if memory serves me right you can use the development snapshot to overcome it temporarily until they roll it out.
> 2 votes

# Answer
you can look for simple eric martin plugin which gives a simple js library which you can put at module level or theme level and you have to add js snippet to tell eric matin plaugin to pull the content for a url which should be your confirmation page.
> 2 votes

# Answer
you can try this: Simple Dialog module

i hope it works for you.
> 1 votes

# Answer
all you need dude is to install Nice messages module and the confirmation message will show as popup message thats it ;) .
> 0 votes

---
Tags: 7, webforms
---


title: Migrate custom source plugin not found

text:
# Question
Title: Migrate custom source plugin not found
I have a fairly simple D6-\>D8 migration, and I need a custom source plugin for one of my node migrations. As far as I can tell, I have everything written and structured properly, but when I click on the migration group in the admin UI, I get a message that my source plugin doesn't exist.

Here's the relevant part of my node migration config:

In /my-module/config/install/migrate\_plus.migration.video.yml:

```
id: video
label: Video
migration_tags:
  - Drupal 6
deriver: Drupal\node\Plugin\migrate\D6NodeDeriver
migration_group: node
source:
  plugin: mrctvVideoSource
  node_type: video
process:

```

and my source plugin in /my\_module/src/Plugin/migrate/source/mrctvVideoSource.php:

```
namespace Drupal\migrate_mrctv\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Row;

/**
 * Source plugin for MRCTV video nodes.
 *
 */
class mrctvVideoSource extends SqlBase {

  /**
   * @MigrateSource(
   *   id = "mrctvVideoSource"
   * )
   */
  public function query() {
    return $this->select('view_videos', 'vv')
                ->fields('vv', array_keys($this->fields()));
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'video_data' => $this->t('Video Data'),
      'thumbnail_data' => $this->t('Thumbnail Data'),
      'show_ads' => $this->t('Show Ads'),
      'raw_s3_file' => $this->t('Raw S3 File'),
      'nid' => $this->t('Node ID'),
      'vid' => $this->t('Version ID'),
      'title' => $this->t('Nond Title'),
      'node_created' => $this->t('Created'),
      'node_changed' => $this->t('Changed'),
      'node_uid' => $this->t('Node User'),
      'node_body' => $this->t('Body'),
      'teaser' => $this->t('Teaser'),
      'revsion_uid' => $this->t('Revision UID'),
      'log' => $this->t('Revision Log'),
      'timestamp' => $this->t('Revision Timestamp'),
    ];

    return $fields;
  }
}

```

From what I can tell, I have everything named and annotated properly and in the correct locations, but I'm obviously missing something. What is it?

Thanks.

**UPDATE:** Per Mike Ryans'suggestion below, I changed the id of my plugin (after clearing cache) from 'mrctvVideoSource' to 'mrctv\_video\_source', both in the migration yml file and the id annotation in my plugin definition (is there anywhere else I need to change it?). But now, after uninstalling my module (and having to manually delete the config records in the config database again, config\_devel doesn't seem to be clearing anything out), my node migrations are not even listed on the Migration page. Sigh. Still troubleshooting...

# Answer
> 1 votes
Obvious question - did you rebuild cache (drush cr)?

The only odd thing I see is having a mixed-case plugin ID - what if you made it all lower-case?

# Answer
> 3 votes
I think you need to have your annotation outside of the class

```
/**
 * Source plugin for MRCTV video nodes.
 *
 * @MigrateSource(
 *   id = "mrctvVideoSource"
 * )
 */
class mrctvVideoSource extends SqlBase {

```

# Answer
> 0 votes
I had a similar `PluginNotFoundException` for my custom source plugin today. It turned out that during a faulty configuration merge (via git) and the following configuration import my migration plugin got deactivated.

My migration group was still showing up in the Migrate UI because i was using a `drush config-import` after every change in the fieldmapping:

`drush config-import --partial --source="modules/my_migration/config/install"`

Because I basically hid the symptoms of a disabled module with the config-import, it took me some time to find the real problem.

---
Tags: 8, migrations, plugins
---


# Question
Title: programmatically attaching file to file media
I am trying to programmatically attach a file to a node, using the media module now included in core as of Drupal 8.5.0.

I wrote this drush script to stub out the creation of a new `file` media content piece.

```
<?php

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
use \Drupal\media\entity\Media;

$file = file_save_data(uniqid(), 'public://test' . uniqid() . '.txt');

$drupalMedia = Media::create([
  'bundle' => 'file',
  'uid' => '0',
  'file' => [
    'target_id' => $file->id(),
  ],
]);

$drupalMedia->setName(uniqid())
  ->setPublished(TRUE)
  ->save();

```

When I navigate to the site's media at `admin/content/media`, I see my media listed:

But when I edit the piece of media, my text file is not attached to it:

There are no error messages in watchdog.

What am I missing? What do I need to do to attach the file to the media?

# Answer
> 2 votes
The key for file needed to be `field_media_file` instead of `file`.

---
Tags: 8, media
---


title: How to properly handle migration errors

text:
# Question
Title: How to properly handle migration errors
I've got some migrations and they are basically doing their job. My problem is that errors in the data source end up in a WSOD in Migrate Tools UI, without any human readable error message (when I click on "List migration").

E.g. my source usually responds something like

`{success: true, result: {my_dataset: {data1: 'Alice', data2: 'Bob'}}}`

and in my YML I've got something like

```
source:
  plugin: url
  data_parser_plugin: json
  item_selector: /result/my_dataset
  fields:
    -
      name: data1
      label: 'Just an example'
      selector: data1

```

Today my source went down and returns a HTTP 500 with

`{success: false, message: 'We are working on it, try later...'}`

How can I force the Migrate Tools UI to display an error message and stay in the admin theme, instead of a WSOD?

# Answer
> 0 votes
Came across this question trying to resolve a similar migration error -- try using the Drush command line tools instead of the UI and use the -d flag so it shows all of the errors during a migrate command, ex:

```
drush -d migrate:status

```

---
Tags: 8, migrations
---


# Question
Title: How to have #description in form to be below title and above field?
How can I place Description below Title and above field ?

```
 $form['term-selection']['autocomplete'] = array(
      '#title' => variable_get('autocomplete_sync_shs_autocomplete_headline',t('Type in directly')),
      '#description' => variable_get('autocomplete_sync_shs_autocomplete_info',t('')),
      '#type' => 'textfield',
      '#autocomplete_path' => 'third-level-auto-suggest/autocomplete-taxonomy-term/'.$field_name.'/'.$entity_type.'/' . $node_type ,
      '#states' => array(
         'disabled' => array(
           ':input[name="widget-selection"]' => array('value' => 1 ),
         ),
      ),
      '#default_value' => $default_autocomplete,
    );

```

The output I get is

# Answer
User #after\_build at the end of your hook\_form\_alter.

```
$form['#after_build'][] = 'MODULE_NAME_move_description_up_after_build';

```

See below function to move the description in between the title and field.

```
/**
 * build function
 * @param type $form
 * @param type $form_state
 * @return type
 */
function MODULE_NAME_move_description_up_after_build($form, $form_state) {
  drupal_add_js('jQuery(document).ready(function ($) {
    $("label ~ div.description").each(function(index, element) {
      $(this).insertBefore($(this).prev("input"));
    });
  });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

  return $form;
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: How do I create a workflow that creates multiple nodes?
I'm recreating my pages in Drupal 8 for a platform upgrade. One thing I've identified for this upgrade is the need for a workflow that creates multiple nodes before it's actually finished. If a user creates node of type A, it automatically creates a second node of Type be and auto-fills an entity reference field with whatever nid Node A was given. I'm HOPING this is something I Can create easily, through a form builder or something like that.

I'm not sure what the best option is for this, but I do need to find a way to simplify this workflow. I think I'll need rules a part of it, but I'm not sure at all one way or the other.

# Answer
> 0 votes
Here is a solution I came up with. Create a custom module and in your `MODULENAME.module` file implement `hook_form_alter` to add a custom submit handler `MODULENAME_add_story`

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  // if creating node of type A (article is machine name)
  if($form_id == 'node_article_form') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_add_story';
  }
}

```

In the custom submit function create the referenced node and save the reference on the original node

```
function MODULENAME_add_story($form, $form_state) {

  $article = $form_state->getFormObject()->getEntity();
  $aid = $article->id();
  $uid = $article->getOwnerId();

  // Create node of type B (story is machine name)
  $story = \Drupal\node\Entity\Node::create([
    'type'        => 'story',
    'title'       => 'New auto created story new',
    'uid' => $uid,
    //set other fields
  ]);
  $story->save();

  //set the reference and save
  $article->field_stories[] = ['target_id' => $story->id()];
  $article->save();
}

```

So when you create node of type `article` a node of type `story` is also created and referenced from `article`.

---
Tags: 8, nodes, forms
---


# Question
Title: url of each listed nodes in a view using the content format
How can I display a node link for each node listed in a view with a content format parameter?

I have set a view with a content format teaser and the template is node--article--teaser.html.twig.

`<a href="{{ url }}" rel="bookmark">` displays the page link where the view is displayed, not the content.link.

I cannot figure out why it does not work in my site and what could interfere with it.

The only way around I found was to get the node ID with `content.links['#lazy_builder'][1][0]`.

Do you have any idea?

# Answer
Read the comments of the default node.html.twig under /core/modules/node/templates/. Any variable listed there should also work in node--article--teaser.html.twig.
> 1 votes

---
Tags: 8, theming, nodes
---


# Question
Title: Local tasks not correctly limited to base_route
I want to create a customized media library for my editors, with a tab navigation similar to the tabs on core's `admin/content` view. It basically works, but I also want to add a tab leading to a specific "media" taxonomy vocabulary used by my media entities. As soon as I add the taxonomy tab to my YML file, the `base_route` filter no longer works.

Screenshot with correct behaviour on view pages:

Screenshot with unwanted tabs on taxonomy page:  This is my custom modules' `links.task.yml`.

```
# a common view page for all media types
wt_media.media_list:
  route_name: view.medialibrary.medialibrary
  base_route: view.medialibrary
  title: 'All media types'
# a view page only for images
wt_media.image_list:
  route_name: view.medialibrary.imagelibrary
  base_route: view.medialibrary
  title: Images
# a view page only for videos
wt_media.video_list:
  route_name: view.medialibrary.videolibrary
  base_route: view.medialibrary
  title: Videos
# a view page only for documents/files
wt_media.file_list:
  route_name: view.medialibrary.filelibrary
  base_route: view.medialibrary
  title: Documents
# as soon as I activate the following entry, all the tabs are shown
# on every taxonomy overview page, this is not wanted
wt_media.manage_taxonomy:
  route_name: entity.taxonomy_vocabulary.overview_form
  route_parameters:
    taxonomy_vocabulary: media
  base_route: view.medialibrary
  title: Manage Categories

```

How can I prevent my custom tabs from appearing on the taxonomy overview pages?

# Answer
> 0 votes
You can use `hook_menu_local_tasks_alter()` to see what all elements are added and can remove elements based on any conditions you like.

---
Tags: 8, navigation
---


# Question
Title: Products containing a hyphen or numbers not shown or wrong relevance
I have an external Apache Solr Server, with Search API and Search API Views.

When we search for ordinary products, they are shown correctly, with the correct descending relevance order.

When we search for a product with the exact name: **"Productx-123W**" it is showing in this order (with highlighted terms by search function):

* **Productx**-123D
* **Productx**-123S
* **Productx**-123
* **Productx**-**123W**

So the exact product name is only shown on the 4th place, while all other products with no hyphens or `-` in them have the correct displayed order in the results.

It is like the hyphen splits the word in two.

Secondly, I have a product: **Product20001w** When I look for this search term: "**2000**" nothing is shown. It's like the numbers on the end confuse the server. When I look for "**2001w**", it shows the right products which have partially this "2001w" in their name.

Anyone knows how to fix this?

# Answer
> 1 votes
It is basically a feature of Word Delimiter Filter to allow matching of words on case-change, alphanumeric boundaries, and non-alphanumeric chars, so when typing "wifi", "wi fi" could match documents containing "Wi-Fi". That is why Product-123A is split to match more products. See: Intra-Word Delimiters.

So you can either disable *WordDelimiterFilter*, or customize it. For example:

```
<filter class="solr.WordDelimiterFilterFactory"
        protected="protwords.txt"
        generateWordParts="1"
        generateNumberParts="1"
        catenateWords="0"
        catenateNumbers="0"
        catenateAll="0"
        splitOnCaseChange="0"
        preserveOriginal="1"/>

```

Since the second part of your word consist number (e.g. *123W*), you may try to enable `catenateWords` and `catenateNumbers` (set to `1`) in your `schema.xml` file and apply the changes to your hosted Solr server.

You can also provide some customization using`wdftypes.txt` file, see: SOLR-2059.

However, if you want to keep the feature as it is (without modifying any Solr config files), you can also consider increasing the score for certain fields, such as titles (e.g. a product name). So your `Productx-123W` phrase after a word split will match higher on documents with partial matches such as `123W` in specific fields.

Related posts:

---
Tags: search
---