# Question
Title: Dependency inject a class with values from a config object?
Is it possible to DI dependencies in Drupal 8 *but* initialize it with values from a config object?

For example, SoapClient requires specifying the WSDL when called. I have different WSDL URLs depending on what environment I am using (test/prod etc).

I know you can do this from the services yaml file, but I have not read of a way where you can reference a value or value(s) from a config object.

My ultimate goal is to create a decorator or factory for SoapClient, but I'm not sure which.

edit: updated with code.

An interface:

```
<?php

namespace Drupal\iana_netforum_auth\Factory;

use SoapClient;

interface SoapClientFactoryInterface {

  /**
   * Create a SoapClient.
   *
   * This method should prepopulate the SoapClient with values from our
   * module configuration so it is ready to use.
   *
   * @return SoapClient
   */
  public function create() : SoapClient;

}

```

The factory:

```
<?php

namespace Drupal\iana_netforum_auth\Factory;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\iana_netforum_auth\Exception\NetforumException;
use SoapClient;

class SoapClientFactory implements SoapClientFactoryInterface {

  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
  }

  public function create() : SoapClient {
    $config = $this->configFactory->get('iana_netforum_auth.settings');
    $arguments = [];

    try {
      if ($config->get('mode') == 'live') {
        $endpoint = $config->get('live_endpoint');
      }
      else {
        $endpoint = $config->get('dev_endpoint');
        $arguments = [
          'trace' => $config->get('enable_trace'),
          'exceptions' => $config->get('enable_exceptions')
        ];
      }

      return new SoapClient($endpoint, $arguments);
    }
    catch (SoapFault $error) {
      throw new NetforumException('Invalid WSDL endpoint specified.');
    }
  }

}

```

The class:

```
class NetforumClient implements NetforumClientInterface {

  protected $username;
  protected $password;
  protected $token;
  protected $authorizationHeaders;

  /**
   * Drupal\Core\Config\ConfigFactoryInterface definition.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface definition.
   *
   * @var \Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface
   */
  protected $soapClient;

  /**
   * Class constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   An instance of ConfigFactoryInterface.
   * @param \Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface $soap_client_factory
   *   An instance of SoapClientFactoryInterface.
   */
  public function __construct(ConfigFactoryInterface $config_factory, SoapClientFactoryInterface $soap_client_factory) {
    $this->configFactory = $config_factory;
    $this->soapClient = $soap_client_factory->create();
  }

```

# Answer
> 5 votes
Not sure which part exactly is unclear. There are lots of examples in core.services.yaml that inject the config.factory service to read a configuration object, for example this:

```
diff.formatter:
  class: Drupal\Core\Diff\DiffFormatter
  arguments: ['@config.factory']

```

The constructor for that then looks like this:

```
/**
 * Creates a DiffFormatter to render diffs in a table.
 *
 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
 *   The config factory.
 */
public function __construct(ConfigFactoryInterface $config_factory) {
  $config = $config_factory->get('system.diff');
  $this->leading_context_lines = $config->get('context.lines_leading');
  $this->trailing_context_lines = $config->get('context.lines_trailing');
}

```

Once you have the config object, you get the configuration you want and pass it along to the SoapClient constructor.

---
Tags: 8, dependency-injection
---


# Question
Title: I need a .schema.yml file when I create a new custom field?
I just read Create a custom field type and I can't find a lot of information about the .schema.yml file. So, I just create a custom field without the .schema.yml file and I see that if I add my custom field in a content type and I export my config the field is exported with all the configuration.

So we really need the schema.yml file when I create a new custom field?

# Answer
To make sure configuration and default values are using the correct types, there can be tricky bugs related to float/int for example.

If you have interface strings in your settings, you can also use the config schema definitions to make them translatable.

And it can be used to validate configuration.

Config schema is not enforced by default, see https://www.drupal.org/node/2625212. But it enforced by default in tests, so try to write a test that creates a field of your type and it will complain and tell you what schema is missing.
> 5 votes

---
Tags: 8, configuration
---


# Question
Title: Install a theme with its demo content -- via command line?
The tutorials I've seen all want me to use phpMyAdmin. Here is an example that's very apropos since my theme is Zircon. https://www.weebpal.com/guides/step-step-guide-install-drupal-8-theme AFAIK I don't have MyPHPAdmin and I don't have access to it. What I do have is sudo access on the Ubuntu 16.04 server. I'm using Drupal 8

# Answer
> 1 votes
You can import the database using drush rather than phpMyAdmin.

Create a standard drupal 8 site, go to the /sites/default directory and run

```
drush sql-cli < databasefilename.sql

```

See the importing database section here http://tylerfrankenstein.com/code/use-drush-export-import-drupal-mysql-database-dump-file

---
Tags: theming
---


# Question
Title: Create short link automatically with ShURLy
I am using the ShURLy module to create short links for nodes. I would like to be able to create the short links when nodes are published, automatically, without having to do the extra steps of clicking on the Bookmarklet which opens a new page where I create the short link by clicking on a button/link.

How can I achieve this?

**update**

I am using workbench so I added

```
function my_node_workbench_moderation_transition($node,
$previous_state, $new_state) {
// Generate the short link when it is published.
  if ($new_state == 'published' && $previous_state != $new_state) {
    $link = my_node_create_short_link($node->nid);
  }
}

```

and the function `my_node_create_short_link` with shorten (shorten\_url)

```
function my_node_create_short_link($node_id) {
 // Do not create the short link if already exists.
  $link = my_node_short_link_get($node_id);
  if ($link) {
      return $link;
  }
  else {
    $link = shorten_url(url('node/' . $node->nid, array('absolute' => TRUE)));
    // Insert the link
    my_node_short_link_insert($node->nid;, $link);
    cache_set($node->nid;, $link);
    return $link;
  }

```

}

# Answer
> 1 votes
As per the current module functionalities it does not seem to have that feature. So I think you need to create custom module.

In your custom module you will require to use hook\_node\_insert (For Drupal 7) this hook to execute after each node is added. Then Shurly provides API to create short link, using those APIs you can create short link as an when required.

Hope this helps.. :)

---
Tags: 7, nodes, workbench
---


# Question
Title: Override specific routing from a core module
I want to stop anonymous users being able to access a specific set of routes offered by the core/forum module.

specifically:

```
forum.index:
  path: '/forum'
defaults:
  _controller: '\Drupal\forum\Controller\ForumController::forumIndex'
  _title: 'Forums'
requirements:
  _permission: 'access content'

```

and

```
forum.page:
  path: '/forum/{taxonomy_term}'
defaults:
  _controller: '\Drupal\forum\Controller\ForumController::forumPage'
  _title_callback: '\Drupal\taxonomy\Controller\TaxonomyController::termTitle'
requirements:
  _permission: 'access content'

```

I just need to add: `_user_is_logged_in: 'TRUE'` to the routes' requirements.

How does one do this without 'hacking' core?

I have alternative routes for the above in my own module - with different names and controllers and in an ideal word I would also wish to redirect both those routes through my own. However, for a start I will take being able to stop anonymous users seeing my forums.

# Answer
> 13 votes
You can override route details in a route subscriber:

*src/Routing/RouteSubscriber.php:*

```
<?php

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('forum.index')) {
      $route->setRequirement('_user_is_logged_in', 'TRUE');
    }
  }

}

```

*example.services.yml:*

```
services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

See Altering existing routes and adding new routes based on dynamic ones

If you want you can also replace the core classes with your own classes. You can have multiple routes for one class. Then you don't need a redirect.

---
Tags: 8, routes
---


# Question
Title: How to remove the zip code field from the checkout page?
I have a Drupal 8 website with Drupal Commerce 2.x. I want to disable the zip code field in the checkout page. How can I do this?

# Answer
> 2 votes
Address modifications should be done on the Address module level, not on the Commerce level.

You can disable the zip code for a specific country by subscribing to the AddressFormatEvent and removing the %postalCode token from the $definition\['format'\] string. A str\_replace('%postalCode', '', $definition\['format'\]) should do it.

You can find an example event in this blog post.

# Answer
> 0 votes
Depends on which checkout pane you want to remove it from.

1. If you want to remove it from the shipping address, you will need to create a custom form widget for the address module.
2. If you want to remove it from the billing address, you would need to extend the `PaymentGateway` Commerce plugin and the `PaymentMethodAddForm` PluginForm.

Below are examples using Stripe and removing the postal\_code from the billing address. As far as I know, you would never want to do this.

Example Stripe override: `example\Plugin\Commerce\PaymentGateway\ExampleStripe.php`

```
<?php

namespace Drupal\example\Plugin\Commerce\PaymentGateway;

use Drupal\commerce_stripe\Plugin\Commerce\PaymentGateway\Stripe;

/**
 * Provides the Example customized Stripe payment gateway.
 *
 * @CommercePaymentGateway(
 *   id = "example_stripe",
 *   label = "Example Stripe",
 *   display_label = "Example Stripe",
 *   forms = {
 *     "add-payment-method" = "Drupal\example\PluginForm\example\PaymentMethodAddForm",
 *   },
 *   payment_method_types = {"credit_card"},
 *   credit_card_types = {
 *     "amex", "dinersclub", "discover", "jcb", "maestro", "mastercard", "visa",
 *   },
 * )
 */
class ExampleStripe extends Stripe {

}

```

And then the example PaymentMethodAddForm override:

```
<?php

namespace Drupal\example\PluginForm\ExampleStripe;

use Drupal\commerce_stripe\PluginForm\Stripe\PaymentMethodAddForm as StripePaymentMethodAddForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class PaymentMethodAddForm.
 *
 * Removing the postal code from billing address.
 *
 * @package Drupal\example\PluginForm\ExampleStripe
 */
class ExamplePaymentMethodAddForm extends StripePaymentMethodAddForm {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    /** @var \Drupal\commerce_order\Entity\Order $order */
    if ($order = $this->routeMatch->getParameter('commerce_order')) {
      // Not recommended.
      $form['billing_information']['field_address']['postal_code']['#access'] = FALSE;
    }
    return $form;
  }

}

```

Finally, you would need to go into the Payment Gateway configuration page and select or create a new payment gateway using your new version of the plugin.

# Answer
> 0 votes
The easiest and simplest way is to add an after build function to the address element. In this the whole element will be built and allow you to remove access to the postal code element.

Remember to use `['#access'] = FALSE` and provide a default value. Otherwise there could be unknown validation issues

---
Tags: 8, commerce
---


# Question
Title: Configuration export/import doesn't work
I did a `drush config-export staging` on a local version of my site then a `drush config-import staging` on the server. It imported all the taxonomy vocabulary but no terms. I also tried it via the UI (*Configuration-\>Development-\>Configuration Synchronization*). Is this a bug or just the unfinished nature of Drupal 8?

# Answer
> 13 votes
*Configuration management* is exporting exactly what it was designed to do: *Export the configuration settings*. The actual taxonomy terms themselves are sitting in the `taxonomy_term_field_data` table in the database.

# Answer
> 6 votes
This is by design as taxonomy terms is the content, not configuration.

> Features deals exclusively with configuration and so won't include support for content entities such as taxonomy terms.

Source: Exporting of Taxonomy terms.

---

However you can use other modules which may work with content such as Default Content module which supports taxonomy terms. Or check Deploy module for content staging.

For example check out this patch for Default Content module: Drush comand to export all items, once applied, you can export all terms from the specific vocabulary using `drush`, e.g.

```
drush dcer taxonomy_term vid my_vocabulary --folder=dest/

```

See also: How do I export my site structure?

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


# Question
Title: How do I programmatically show a view block?
I created a view block, whose machine name is "news."

How do I display it using `module_invoke()` and the machine name of the view?

# Answer
> 66 votes
Use `views_embed_view()`:

```
echo views_embed_view('view_machine_name', 'block_1');

```

You can find out the display name by clicking the tab and check its name in the address bar of your browser: `#views-tab-block_1` gives you `block_1`.

# Answer
> 24 votes
If you want to pass a parameter to the view use:

```
echo views_embed_view('view_machine_name', 'block_1', $param);

```

For example:

```
echo views_embed_view('view_machine_name', 'block_1', $node->nid);

```

or:

```
echo views_embed_view('view_machine_name', 'block_1', $nid, $uid);

```

# Answer
> 8 votes
tostinni's answer is the correct one in most cases. However, if you want to include the View title, it is a bit more ugly.

From the `views_embed_view()` documentation:

> Note that this function does NOT display the title of the view. If you want to do that, you will need to do what this function does manually, by loading the view, getting the preview and then getting `$view->get_title()`.

For example:

```
$name = 'view_machine_name';
$display_id = 'block_1';
$view = views_get_view($name);
if (!$view || !$view->access($display_id)) {
  return;
}
$view_content = $view->preview($display_id);
$title = $view->get_title();

```

*Updated*: @rojosnow noted that the docs point out you must get the preview *before* calling `get_title()` so I've flipped those two lines around.

# Answer
> 1 votes
This Worked for me :

```
$view = views_get_view('view_machine_name');
$view->set_display('Master');
$view->get_title();
$response = $view->preview('You_Block_id');

```

//and called it in html like this//

```
<div class="col-md-4 col-sm-6">
<div class="blocksOuterWrapper companyNewsWrapper">
'.$response.'
</div>
</div>

```

# Answer
> 1 votes
Note, for me the default block (with no name) is called `block` rather than `block_1`:

```
<?php echo views_embed_view('news_archive', 'block'); ?>

```

# Answer
> 0 votes
Also building on tostinni's answer:

If you don't want any HTML to show up if the view has no results. Also, add a title, but only if there are results.

```
if (array_filter(views_get_view_result('view_machine_name', 'block_1'))) {
    print '<h2 class="my-view-block-title">Special Title</h2>';
    print views_embed_view('view_machine_name', 'block_1');
}

```

# Answer
> 0 votes
You could render your block instead of rendering the views by the following code.

```
<?php
 $block = block_load($module, $delta);
 $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
 $output = render($render_array);
 print $output;
?>

```

# Answer
> 0 votes
From my own experience, you can transform a path to a view title or content with a function like the following.

```
<?php
function view_path_to_title($path)
{
  // only if your path is a URL alias
  $sql = "SELECT src FROM {url_alias} WHERE dst = '%s'";
  $src = db_result(db_query($sql, $path));

  // if you do not use URL aliases, you probably use $path here instead of $src
  $menu_item = menu_get_item($src);

  // make sure it worked as expected
  if(!empty($menu_item)
  && $menu_item["page_callback"] == "views_page"
  && count($menu_item["page_arguments"]) >= 2)
  {
    $args = $menu_item["page_arguments"];
    $view = views_get_view($args[0]);
  }
  else
  {
    $view = null;
  }

  if ($view)
  {
    // just loading a view is not quite enough, we have to setup the
    // arguments, including the display, and the "execute" the view
    $view->set_display($args[1]);
    array_shift($args); // view name
    array_shift($args); // display name
    $view->set_arguments($args);
    $view->execute();
    $title = $view->get_title();
    if($title)
    {
      return $title;
    }
  }

  // some "random" default
  return $path;
}

```

To render the view, use `$view->render()` instead of `$view->get_title()`.

For sure, until I properly called the `$view->execute()`, nothing worked right. I would get empty strings (maybe null) as return values.

---
Tags: 7, views, blocks
---


# Question
Title: How to make custom taxonomy pages per term based on fields?
I have a bunch of taxonomy terms, one for each county in a state.

I am going to use the taxonomy pages as landing pages in a Google Adwords campaign that is customized per county.

So, I have some boilerplate text that I want to use on all term pages, but I want to substitute the county name (which is the term name) and the biggest city in the county (which is input as a text field on the taxonomy term).

What's a quick way to do this in Drupal 8? I tried to edit the **Taxonomy Term** view, but this is showing the content tagged by the term; in my case, there is no content tagged by the term. I want to use the term name and field data on the term to customize the boilerplate text.

# Answer
I solved this with Panelizer and a custom block made in Views.

```
View of taxonomy terms, custom block
Contextual filter- taxonomy term: term ID
Provide default value: Term ID from URL

Pathauto pattern for taxonomy terms:
[term:tid]/mylinkpath/[term:name]

Go to taxonomy term display and add panelizer, then add custom views block.

```
> 0 votes

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


# Question
Title: Expose (other) user's role to anonymous using views
## Setup

On my site I have created two new, different roles (say role A and B). New users get assigned one of these roles.

Using Views I have generated a user listing, i.e. a view showing all users having either of role A or B. This overview listing shows some user information, including the role that the respective user in the listing has. The role is pulled in using a field making use of user relationship: *(Owner: User) User relationship: Roles*

The anonymous user also has *View user information* permission.

## Issue

The user listing view works fine, if the user viewing it is authenticated (i.e. logged in).

However, if the user is anonymous (i.e. not logged in), the role does not get displayed in the user listing view.

## Desired outcome

I would like all users, including the anonymous user, to be able to view the roles in the user listing.

**Question(s)**

* How can this be achieved using Views?
* If this can not be achieved using Views, then how?

# Answer
> 0 votes
Ok, I figured it out with help from @Dropa. What I had to do was to build my view in a different way than I initially had it set up.

Initially I had my view built as showing fields from profile, and then I pulled in the user information through a relationship.

What I had to do was to switch it around and create the view showing fields from user. This allowed me to display the user information, including the role info that I am after. All other desired information (e.g. other information from the profile module) is then pulled in through a relationship.

---
Tags: views, 8, users
---


# Question
Title: How to use two pages of a View with the same path depending on users's profile?
I created a View on a custom Content Entity.
I'd like to have 2 pages:

* the first with all the fields from my entity, no filters, accessible by users with Edit rights on the entity,
* the second one with some of the fields, filtered by one criteria, accessible by users with View rights on the entity.

And, of course, with the same path, e.g. \[mysite\]/myEntity.
How do I do that?
I use Drupal 8.3.4.

# Answer
> 1 votes
In Drupal 7 this was quite easy to implement just using Views. In D8 I couldn't manage to implement it only with Views.

You can create a panel page with two different variants. Place the relevant block in each variant and control the accessibility though the 'Page access'. (I used roles but you can even create your custom condition)

---
Tags: views, 8
---


# Question
Title: How to write custom node_access that works with searchapi?
I'm trying to write a custom node access module, implementing hook\_node\_access.

I have a searchapi index of all my nodes, which I would like to return results that obey the hook\_node\_access conditions (at the time of indexing, at least) without requiring additional postprocessing.

In order to do this, I am enabling the 'Node access' filter on the search index ('Add node access information to the index.') I'm using search\_api\_solr, search\_api\_views, and the 'retrieve result data from solr' option. The indexes have been rebuilt.

However, when I look at the results of a search performed as an anonymous user, I find that nodes for which my node\_access returns NODE\_ACCESS\_DENY are being included. In other words, it seems to be ignoring my node\_access function.

Further investigation reveals that the SearchApiAlterNodeAccess class is adding Grant information to the index. I don't really understand the Grants system, but I guess it's an alternative way of controlling individual node access. I don't have any custom node\_grants, so as a result, each node which fails node\_access is given the default realm:all, gid:0 grant. And then the \_search\_api\_query\_add\_node\_access function adds an or-condition for any nodes with appropriate grants, which for anonymous users turns out to be realm:all, gid:0.

In other words, within the searchapi system, it looks like node\_access is bypassed by node\_grants. Even though within node\_access itself, node\_grants are only considered if hook\_node\_access has been inconclusive.

(For reference, my node\_access table contains a single row: nid=0, gid=0, realm=all, grant\_view=1.)

I'm sure I'm missing some vital logic here. Any suggestions?

# Answer
Answering my own question: the solution seems to be to modify the search to explicitly add a condition for the grant that I'm interested in.

In this case, it means modifying the view to add a filter criteria: Node access information = node\_access\__all
> 0 votes

---
Tags: views, nodes, search, security
---


# Question
Title: How to make sure my CSS file loads last?
I am working on a module that should override some theme specific settings. The issue is that I cannot get my CSS to override the theme's.

I include the library in `hook_page_attachments` like so:

```
function mymodule_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'mymodule/overrides';
}

```

and

```
function whitelabel_library_info_build() {
  $libraries['overrides']['css']['theme']['path/to/override.css'] = ['weight' => 100000];
    }
  }
  return $libraries;
}

```

Looking at the the entire list of CSS files included it is there. But still too high. How can I move it even lower?

```
<style media="all">
@import url("/core/assets/vendor/normalize-css/normalize.css?osxmg2");
@import url("/core/themes/stable/css/system/components/ajax-progress.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/align.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/autocomplete-loading.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/fieldgroup.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/container-inline.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/clearfix.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/details.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/hidden.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/item-list.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/js.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/nowrap.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/position-container.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/progress.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/reset-appearance.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/resize.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/sticky-header.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/system-status-counter.css?osxmg2");
@import url("/core/themes/stable/css/system/components/system-status-report-counters.css?osxmg2");
@import url("/core/themes/stable/css/system/components/system-status-report-general-info.css?osxmg2");
@import url("/core/themes/stable/css/system/components/tabledrag.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/tablesort.module.css?osxmg2");
@import url("/core/themes/stable/css/system/components/tree-child.module.css?osxmg2");
@import url("/core/themes/stable/css/contextual/contextual.module.css?osxmg2");
@import url("/core/assets/vendor/jquery.ui/themes/base/core.css?osxmg2");
@import url("/core/assets/vendor/jquery.ui/themes/base/button.css?osxmg2");
@import url("/core/assets/vendor/jquery.ui/themes/base/resizable.css?osxmg2");
@import url("/core/assets/vendor/jquery.ui/themes/base/dialog.css?osxmg2");
@import url("/core/themes/stable/css/quickedit/quickedit.module.css?osxmg2");
@import url("/core/assets/vendor/farbtastic/farbtastic.css?osxmg2");
@import url("/core/themes/stable/css/toolbar/toolbar.module.css?osxmg2");
</style>
<style media="all">
@import url("/modules/contrib/devel/css/devel.toolbar.css?osxmg2");
</style>
<style media="screen">
@import url("/core/themes/stable/css/tour/tour.module.css?osxmg2");
</style>
<style media="all">
@import url("/core/themes/stable/css/contextual/contextual.toolbar.css?osxmg2");
@import url("/core/themes/stable/css/toolbar/toolbar.menu.css?osxmg2");
@import url("/core/themes/stable/css/contextual/contextual.theme.css?osxmg2");
@import url("/core/themes/stable/css/contextual/contextual.icons.theme.css?osxmg2");
@import url("/core/assets/vendor/jquery.ui/themes/base/theme.css?osxmg2");
@import url("/core/themes/seven/css/components/quickedit.css?osxmg2");
@import url("/core/themes/stable/css/quickedit/quickedit.theme.css?osxmg2");
@import url("/core/themes/stable/css/quickedit/quickedit.icons.theme.css?osxmg2");
@import url("/core/themes/stable/css/color/color.admin.css?osxmg2");
@import url("/core/themes/stable/css/toolbar/toolbar.theme.css?osxmg2");
@import url("/core/themes/stable/css/toolbar/toolbar.icons.theme.css?osxmg2");
@import url("/core/themes/stable/css/user/user.icons.admin.css?osxmg2");
@import url("/core/themes/stable/css/shortcut/shortcut.theme.css?osxmg2");
@import url("/core/themes/stable/css/shortcut/shortcut.icons.theme.css?osxmg2");
@import url("/modules/contrib/commerce/css/commerce.icons.css?osxmg2");

```

@import url("/modules/contrib/mymodule/override.css?osxmg2");

```
</style>
<style media="all">
@import url("/core/themes/bartik/css/base/elements.css?osxmg2");
@import url("/core/themes/bartik/css/layout.css?osxmg2");
@import url("/core/themes/classy/css/components/progress.css?osxmg2");
@import url("/core/themes/classy/css/components/dialog.css?osxmg2");
@import url("/core/themes/classy/css/components/action-links.css?osxmg2");
@import url("/core/themes/classy/css/components/breadcrumb.css?osxmg2");
@import url("/core/themes/classy/css/components/button.css?osxmg2");
@import url("/core/themes/classy/css/components/collapse-processed.css?osxmg2");
@import url("/core/themes/classy/css/components/container-inline.css?osxmg2");
@import url("/core/themes/classy/css/components/details.css?osxmg2");
@import url("/core/themes/classy/css/components/exposed-filters.css?osxmg2");
@import url("/core/themes/classy/css/components/field.css?osxmg2");
@import url("/core/themes/classy/css/components/form.css?osxmg2");
@import url("/core/themes/classy/css/components/icons.css?osxmg2");
@import url("/core/themes/classy/css/components/inline-form.css?osxmg2");
@import url("/core/themes/classy/css/components/item-list.css?osxmg2");
@import url("/core/themes/classy/css/components/link.css?osxmg2");
@import url("/core/themes/classy/css/components/links.css?osxmg2");
@import url("/core/themes/classy/css/components/menu.css?osxmg2");
@import url("/core/themes/classy/css/components/more-link.css?osxmg2");
@import url("/core/themes/classy/css/components/pager.css?osxmg2");
@import url("/core/themes/classy/css/components/tabledrag.css?osxmg2");
@import url("/core/themes/classy/css/components/tableselect.css?osxmg2");
@import url("/core/themes/classy/css/components/tablesort.css?osxmg2");
@import url("/core/themes/classy/css/components/tabs.css?osxmg2");
@import url("/core/themes/classy/css/components/textarea.css?osxmg2");
@import url("/core/themes/classy/css/components/ui-dialog.css?osxmg2");
@import url("/core/themes/classy/css/components/file.css?osxmg2");
@import url("/core/themes/classy/css/components/messages.css?osxmg2");
@import url("/core/themes/bartik/css/components/block.css?osxmg2");
@import url("/core/themes/bartik/css/components/book.css?osxmg2");
</style>
<style media="all">
@import url("/core/themes/bartik/css/components/breadcrumb.css?osxmg2");
@import url("/core/themes/bartik/css/components/captions.css?osxmg2");
@import url("/core/themes/bartik/css/components/comments.css?osxmg2");
@import url("/core/themes/bartik/css/components/contextual.css?osxmg2");
@import url("/core/themes/bartik/css/components/demo-block.css?osxmg2");
@import url("/core/themes/bartik/css/components/dropbutton.component.css?osxmg2");
@import url("/core/themes/bartik/css/components/featured-top.css?osxmg2");
@import url("/core/themes/bartik/css/components/feed-icon.css?osxmg2");
@import url("/core/themes/bartik/css/components/field.css?osxmg2");
@import url("/core/themes/bartik/css/components/form.css?osxmg2");
@import url("/core/themes/bartik/css/components/forum.css?osxmg2");
@import url("/core/themes/bartik/css/components/header.css?osxmg2");
@import url("/core/themes/bartik/css/components/help.css?osxmg2");
@import url("/core/themes/bartik/css/components/highlighted.css?osxmg2");
@import url("/core/themes/bartik/css/components/item-list.css?osxmg2");
@import url("/core/themes/bartik/css/components/list-group.css?osxmg2");
@import url("/core/themes/bartik/css/components/list.css?osxmg2");
@import url("/core/themes/bartik/css/components/main-content.css?osxmg2");
@import url("/core/themes/bartik/css/components/menu.css?osxmg2");
@import url("/core/themes/bartik/css/components/node.css?osxmg2");
@import url("/core/themes/bartik/css/components/node-preview.css?osxmg2");
@import url("/core/themes/bartik/css/components/page-title.css?osxmg2");
@import url("/core/themes/bartik/css/components/pager.css?osxmg2");
@import url("/core/themes/bartik/css/components/panel.css?osxmg2");
@import url("/core/themes/bartik/css/components/primary-menu.css?osxmg2");
@import url("/core/themes/bartik/css/components/search-form.css?osxmg2");
@import url("/core/themes/bartik/css/components/search-results.css?osxmg2");
@import url("/core/themes/bartik/css/components/secondary-menu.css?osxmg2");
@import url("/core/themes/bartik/css/components/shortcut.css?osxmg2");
@import url("/core/themes/bartik/css/components/skip-link.css?osxmg2");
@import url("/core/themes/bartik/css/components/sidebar.css?osxmg2");
</style>
<style media="all">
@import url("/core/themes/bartik/css/components/site-branding.css?osxmg2");
@import url("/core/themes/bartik/css/components/site-footer.css?osxmg2");
@import url("/core/themes/bartik/css/components/table.css?osxmg2");
@import url("/core/themes/bartik/css/components/tablesort-indicator.css?osxmg2");
@import url("/core/themes/bartik/css/components/tabs.css?osxmg2");
@import url("/core/themes/bartik/css/components/text-formatted.css?osxmg2");
@import url("/core/themes/bartik/css/components/toolbar.css?osxmg2");
@import url("/core/themes/bartik/css/components/featured-bottom.css?osxmg2");
@import url("/core/themes/bartik/css/components/password-suggestions.css?osxmg2");
@import url("/core/themes/bartik/css/components/ui.widget.css?osxmg2");
@import url("/core/themes/bartik/css/components/vertical-tabs.component.css?osxmg2");
@import url("/core/themes/bartik/css/components/views.css?osxmg2");
@import url("/core/themes/bartik/css/components/buttons.css?osxmg2");
@import url("/core/themes/bartik/css/components/image-button.css?osxmg2");
@import url("/core/themes/bartik/css/components/ui-dialog.css?osxmg2");
</style>
<link rel="stylesheet" href="/core/themes/bartik/css/components/messages.css?osxmg2" media="all" />
<style media="all">
@import url("/core/themes/bartik/css/colors.css?osxmg2");
</style>
<style media="print">
@import url("/core/themes/bartik/css/print.css?osxmg2");
</style>
<style media="all">
@import url("/core/themes/bartik/color/preview.css?osxmg2");
</style>

```

# Answer
After some looking around, I came across `hook_css_alter()`. To *"Alter CSS files before they are output on the page."*

That was not very clear, until I discovered what it did in `outside_in_css_alter()`:

```
function outside_in_css_alter(&$css, AttachedAssetsInterface $assets) {
  // @todo Remove once conditional ordering is introduced in
  //   https://www.drupal.org/node/1945262.
  $path = drupal_get_path('module', 'outside_in') . '/css/outside_in.theme.css';
  if (isset($css[$path])) {
    // Use 200 to come after CSS_AGGREGATE_THEME.
    $css[$path]['group'] = 200;
  }
}

```

It appears that Drupal performs some shuffling magic during aggregation, where the aggregated CSS files are grouped in `CSS_AGGREGATE_DEFAULT` and `CSS_AGGREGATE_THEME`, having the respective weights of 0 and 100.

By moving my CSS file to a group with a higher weight like above, I was able to load my CSS file after the theme files.

This is being covered (any maybe replaced in the future) in this issue: Replace custom weights with dependencies in library declarations; introduce "before" and "after" for conditional ordering.
> 4 votes

# Answer
For JS, Drupal allows you to define dependencies on libraries. Drupal will make the decision as to when your library loads, ensuring all its dependencies are loaded first so your script will work.

For CSS, Drupal defines weights depending on what kind of styles your CSS contains. Base styles come in early and theme styles coming in late.

You do not need to ensure your library loads last. Just define dependencies and weights, and Drupal will ensure it loads in the correct order.

See this page for details.
> -1 votes

---
Tags: 8, theming
---


# Question
Title: How to apply single theme to all webform in drupal 7
I want to create a theme or page layout which will be applied to all the existing and newly created webforms. I want to divide page in 2 parts. In left part want to show webform description and in right part all the webform components.

# Answer
> 0 votes
Easiest way would be using a module like Display Suite to change the page layout of your webforms on it's 'Manage Display' settings. Using a two column layout, you can arrange the content on the left side and webform on the right (webform being all fields you create on the webform part of the node).

If you don't want to use a module just for that, another option would be rewriting the webform node template yourself. For that, copy your theme's node.tpl.php and rename it as node--webform.tpl.php. Note that you would have to print out the correct variables on the markup yourself.

---
Tags: theming
---


# Question
Title: What is the difference between drupal/drupal and drupal-composer/drupal-project packages?
I want to use composer with my future Drupal projects. I installed Composer on my machine and I noticed two packages (drupal/drupal and drupal-composer/drupal-project). When I install the second package, I get a warning message telling that there is no stable version.

What are the difference between those two package?
Is it composer enough for Drupal, or should I use Drush with it?

# Answer
```
drupal/drupal

```

This is the main repository for the Drupal project and is used to generate the tarball which is available for download on Drupal.org. This package is not used (directly) if you are using Composer to manage your codebase.

```
drupal/core

```

This is a subtree split of drupal/drupal repository which contains everything in the parent repo's `/core` directory. This is the package that is used if you are using Composer to manage your codebase.

```
drupal-composer/drupal-project

```

This is a "scaffold" project and serves as a starting point for your root composer.json file. This package isn't maintained by the Drupal Association, but it has become the de facto standard for assembling a Drupal codebase with Composer. It does a few things:

1. It brings in the `drupal/core` package and couple other requirements needed to assemble and run a Drupal site (composer/installers, cweagans/composer-patches) and a few nice-to-haves (drupal/console, webflo/drupal-finder, ...).
2. In addition to the packages listed above, it requires the `drupal-composer/drupal-scaffold` package which is responsible for assembling all the stuff normally provided as part of the tarball that's needed to run a Drupal site that lives *outside* of the /core directory (index.php, update.php, etc).
3. Contains instructions for composer/installers that tells Composer where to put stuff like modules and profiles.
4. Defines the Drupal-specific packagist repository.

Typically, you don't require or clone scaffold projects. They are intended to be used as starting points for projects of your own. You would use the `create-project` command instead:

```
composer create-project drupal-composer/drupal-project

```

There are other scaffold projects out there with more opinions or different focuses (BLT, Drupal CI) and most D8 Distributions provide a scaffold project (Open Social, Lightning, Thunder, etc)
> 4 votes

---
Tags: composer
---


# Question
Title: How can I defer parsing of Javascript on my Drupal 7 site?
I am working on some performance issues for a site I launched recently. Looking at Google's PageSpeed insights I see that High priority on the list is Defer parsing of Javascript. Here is a link:

https://developers.google.com/speed/pagespeed/insights#url=http\_3A\_2F\_2Fwww.gastonia.com\_2F&mobile=false&rule=DeferParsingJavaScript

Wow, over 1 MB of Javascript to parse!! Notice that most of these are from the facebook app (maybe the answers is to remove the fb app, ha!)

Has anyone successfully deferred this in Drupal? I have tried using script defer="defer", and Google gives suggestions like "add script tags in comments and then eval() them, but they give no examples and I am having trouble finding a good tutorial. Any resources or direction is appreciated!

On a side note, if you see anything else in that list that is easily overcomable by drupal, please add a comment. The site in question is http://www.gastonia.com in case you wanted to look at the source code.

# Answer
> 3 votes
Checkout these 2 projects:

* LABjs

> This project aims at support for LABjs in Drupal. LABjs is a JavaScript loader, used by Twitter, Vimeo, examiner.com… which loads (and executes) all scripts in parallel as fast as the browser will allow.
>
> ### Features
>
> Once installed, this module looks for all your JavaScript and LABjsify them automatically. This make all JavaScript are loaded in parallel as maximum as browser supports. The other advantage is that script loading does not block page render.
* HeadJS

> Headjs module uses the totally awesome head.js library by the same author of jQuery Tools to dramatically improve javascript loading times by adding only one script to the document's head and then downloading all other script files in parallel.
>
> Since downloading many small files at the same time is faster than downloading one big file, head.js makes pages load blazingly fast and is especially beneficial for mobile browsers who limit the size of individually cached javascript files.

# Answer
> 5 votes
Given that nearly everything in Javascript for Drupal is triggered by a `$(document).ready()` in jQuery, I don't see any real advantage to using `defer`. In fact, I recently had a real headache from some code I inherited that mixed the two.

One recommendation (I think YSlow suggests it) that you can do is to move scripts to the end, right before the closing `</body>`. This would mean moving the `<?php print $scripts; ?>` in your html.tpl.php. While not deferring the parsing, it does delay the loading so your page renders out quicker, and I have never had any problems in Drupal doing this.

If you do want to add the defer, you need to implement `hook_js_alter`:

```
function mymodule_js_alter (&$javascript)
{
  $javascript['misc/drupal.js']['defer'] = TRUE;
}

```

If you want to defer *everything*, you could try

```
function mymodule_js_alter (&$javascript)
{
  foreach ($javascript as $key => $value) {
    $javascript[$key]['defer'] = TRUE;
  }
}

```

Otherwise, most of the normal Pagespeed fixes don't have much to do with Drupal itself. As long as you deploy with JS and CSS aggregation enabled you should be good. Configure Apache to use compressed responses and decent cache lifetimes and I don't think PageSpeed will complain about much and give you all A's and B's.

# Answer
> 1 votes
Keep in mind that most of these third parties if not all are using CDNs and will often have far future expiration headers. If you look at firebug and make sure that Disable Browser Cache is turned off in NET you will see what most requests look like. I looked at my site and there are only about 4 requests even with facebook and google widgets on the page. The good news is that everyone is going the same thing, if you look at some sites they are way more than 1mb.

It is good practice to reduce the amount of requests each page makes but if you need to keep certain features do to requirements then it is great to use far future expirations and spread requests over parallel servers.

# Answer
> 0 votes
To expand on @mpdonadio this is what defer everything would look like under Drupal 8

```
/**
 * @file
 * Overrides insert.js in Insert module using hook_js_alter
 */
use Drupal\Core\Asset\AttachedAssetsInterface;

/**
 * Implements hook_js_alter().
 */
function override_insert_js_js_alter(&$javascript, \Drupal\Core\Asset\AttachedAssetsInterface $assets)
{
    foreach ($javascript as $key => $value) {
      $javascript[$key]['attributes']['defer'] = TRUE;
    }
}

```

---
Tags: 7, performance
---


# Question
Title: How to remove default 'search' text form search form
I can't seem to figure out how to get rid of the default text "search" on my search form (located here: http://dev.mysourcewise.com/media-center)

I can confirm the following works in Chrome's console:

```
jQuery("#edit-search-block-form--2").val("");

```

However, when I try adding it using Drupal.behaviors or even with the following code in my theme's template.php file, it doesn't work (even though I can confirm the javascript is loaded in the footer):

```
  drupal_add_js('jQuery(document).ready(function () { jQuery("#edit-search-block-form--2").val("");',
array('type' => 'inline', 'scope' => 'footer', 'weight' => 1000)
 );

```

I have tried other methods as well, and nothing is working except entering the the above in the browser console.

# Answer
The Search text in input is created by jQuery from any where. When I search through the JavaScript files, I find the following file:

```
file : /sites/default/modules/hg/sw_tweaks/js/sw_tweaks.js

```

The code

```
//Search Bar @ Top of Home Page
    $(function () {
      $('#edit-search-block-form--2').val("search");
    });
    jQuery('#edit-search-block-form--2').click(function () {
      jQuery('#edit-search-block-form--2').val('');
    });

```

Try to remove this code. I hope this helps you or help you finding the problem.
> 4 votes

# Answer
A good way to do this is to alter the search form via `hook_form_FORM_ID_alter()`, which can be added either in a theme template.php file or in a .module file.

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 */
function YOURTHEMENAME_form_search_block_form_alter(&$form, &$form_state) {
  $form['search_block_form']['#title'] = t('Something'); // Change the label text.
}

```

It is also possible to replace the submission button with an image.

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 */
function YOURTHEMENAME_form_search_block_form_alter(&$form, &$form_state) {
  $form['search_block_form']['actions']['submit']['#type'] = 'image_button';
  $form['search_block_form']['actions']['submit']['#src'] = 'path/to/image';
}

```
> 3 votes

# Answer
It seems that the default placeholder text is set using javascript (probably from the parent theme). This can be easily checked by disabling javascript and loading the demo page again.

A dirty way to deal with ypur problem:

```
drupal_add_js('jQuery(window).
  load(function(){
    jQuery("#edit-search-block-form--2").val("");
  });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 1000)
);

```

This will use the `window.load` event, that will - hopefully - run your code snippet after the theme's javascripts.

Good luck!

P.S.: Of course, the best way to go about this would be to check how the theme's javascripts work and figure out if there is some attribute (probably the `title` one) that is used to set the value of the placeholder.
> 1 votes

# Answer
Rather than using jquery to replace the text better use hook\_form\_alter.

```
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#title'] = t('Text you want'); // Change the text on the label element
}

```
> 0 votes

# Answer
An alternative to altering the template variables is to override the template file.

Switch on template debug to see what template is used in the HTML comments.

Copy that template to your theme folder and change whatever you like.

To tell Drupal about the new template, you must execute `drush cr`.
> 0 votes

# Answer
Use THEMENAME\_form\_alter() in sites/all/themes/THEME/template.php. Place this code in this file.

```
function THEMENAME_form_alter(array &$form, array &$form_state = array(), $form_id = NULL) {
    if ($form_id) {
        switch ($form_id) {
            case 'search_block_form':
                $form['search_block_form']['#attributes']['placeholder'] = t('Search');
        }
    }

```

Obviously, THEMENAME word will be replaced name of theme you use. After placing this code please clear cache.
> 0 votes

# Answer
Combining previous answers:

-use the **hook form alter** (looking at the site, it is indeed the search-block-form), as Jonathan Dalgaard suggested.

-set the **'placeholder' attribute**, as usmanjutt84 suggested.

```
function THEMENAME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['search_block_form']['#attributes']['placeholder'] = t('Enter search term');
}

```
> 0 votes

---
Tags: 7, javascript, search
---


# Question
Title: How to have two domains for same site, but site working in directory in second domain?
Example:

`www.domain1.com -> Drupal site` in root dir (Managed by Apache)

`www.domain2.com/usa -> Drupal site of domain1.com` (Managed by Nginx)

The idea is that `www.domain2.com/<countrycode>` points to the real domain but in a transparent way (User must not see the existence of the real domain).

What I did:

1) Configured nginx as reverse proxy:

```
## HTTP server.
server {
    listen 80; # IPv4

    server_name emed.com, www.emed.com;

    access_log /var/log/nginx/drupal.log;
    error_log /var/log/nginx/drupal.log;

    keepalive_timeout 75 75;

    root /opt/www/web/drupal;
    index index.php;

    include apps/drupal/drupal.conf;

    location /fr/ {
        proxy_set_header Host $host;
        proxy_pass http://localhost:8080/fr/;
        proxy_redirect http://localhost:8080/fr/ http://www.emed.com/fr/;
    }

}

```

2) Configured Apache

```
<VirtualHost *:8080>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
        Alias "/fr" "/var/www/html/drupal7"
</VirtualHost>

```

The problem is that Apache *must* have the `Alias fr` directive, otherwise Drupal generates incorrect URLs:

`www.domain2.com/usa` tries to load assets from `www.domain2.com/sites/...` instead of `www.domain2.com/usa/sites/...`

Is this even possible withouth using Alias? Because the first domain serves on `/` (root)

# Answer
> -1 votes
I think you have to check this module https://www.drupal.org/project/domain it has the solution for this

---
Tags: 7
---


# Question
Title: Modules installed with Composer placed in wrong directory
I'm trying to install modules via Composer. I've set up my `composer.json` file according to Drupal.org's direction. However, the installed modules are being placed inside of `vendor/drupal/`. I'm new to Drupal 8, so I wouldn't be surprised if this is a result of a simple mistake. I'll include my `composer.json` file below:

```
{
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },
    "require": {
        "drupal/admin_toolbar": "^1.19"
    },
    "extra": {
        "installer-paths": {
            "core": ["type:drupal-core"],
            "libraries/{$name}": ["type:drupal-library"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    }
}

```

# Answer
As per what Ivan Jeros said, if you add "composer/installers": "^1.2" to your "require" array, it will add a composer extention that maps to the directories you added:

```
"require": {
        "composer/installers": "^1.2",

```

Otherwise, it puts everything in /vender/drupal
> 1 votes

# Answer
It doesn't sound like your composer.json file is getting read. It's possible having multiple composer files. Are you running your commands from the base folder of your project, beside `composer.json`.

The download directories can customized to match your Drupal layout. For example, this is a popular configuration from Acquia:

```
"extra": {
    "installer-paths": {
        "docroot/core": [
            "type:drupal-core"
        ],
        "docroot/modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "docroot/profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "docroot/themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "drush/contrib/{$name}": [
            "type:drupal-drush"
        ]
    },

```
> 0 votes

---
Tags: installation, 8, composer
---


# Question
Title: Saving a default value when using entityMetaDataWrapper->save()
I have an entity that I import some data into, then create and save via `entityMetadataWrapper->save()`.

When I looked on the form, it *appeared* that a default value that I set up for a field that I'm not importing was being saved, but later when I try to use that field, it's null in the code. If I go to my entity and save it, then the default value is saved and all is right with the world. Is there something special I need to do before `save()` to tell it to use my default value and actually save it?

# Answer
> 1 votes
The default value is used for the widget form only, it won't be automatically set if you use `node_save` or a metadata wrapper. You see it in the form when you edit the newly created entity because there's no value for that field, and Drupal dutifully fills in the default value. It doesn't update the value of that field on the entity, just populates the form input.

You'll need to populate it manually, but you can get the right value with the field API:

```
$instance = field_info_instance('node', 'field_foo', 'article');
$default_value = $instance['default_value'];

```

---
Tags: 7, entities
---


title: Multiple entity reference with Views

text:
# Question
Title: Multiple entity reference with Views
I have a website about movies which are stored in a content type called Movie. Amongst other fields, it's populated with Entity Reference fields such as Director, Actor, Writer, etc... linked to a content type called "Personnality".

For example, Johnny Depp can be referenced as a Director as well as an Actor in a movie called 'The Brave'.

In View, I'd like to list all his movies whether he's an actor or a director. Currently, I do it with several views but for a specific block, I want to feature the best movies of a personnality.

With relationships and contextual filters, I can only pick only one Item.

Is it possible to add multiple reference on the contextual filter ?

Here are some screenshots to help. It's in french, réalisateur = director, actor = casting.

Thanks a lot !

# Answer
> 0 votes
You need to check `allow multiple values` in the **MORE** section of your contextual filter. (You can find it at the bottom).

For example:

---
Tags: views, entities
---


# Question
Title: D8: Why updated paragraph content does not lead to an updated translation?
I created a content type made up with a long-text field and a *multivalue* paragraph field. I create some content adding several paragraphs to the same node, then I choose "Translate" and everything is fine the first time I do this: all original paragraphs appear ready to be translated.

However when I update the original language node adding new paragraphs, these new paragraphs do not appear when editing the translation and I'm forced to delete the latter and create a new translation. Why is this happening?

# Answer
To expand on the comment from @4k4, for most use cases, you want to make the paragraph field untranslatable because it just stores the references to the paragraphs, which are then being translated.

Then you always have the same paragraphs in the same order for all translations.

Translatable paragraph fields are not yet properly supported (this is being worked on in the issue queue) and it should only be done if the paragraph structure must be different for different languages.
> 3 votes

---
Tags: 8, entities, i18n-l10n, paragraphs
---


# Question
Title: Insert node title in the message sent by contact form
I'am looking for a way to insert a node title to mail message sent by contact form in Drupal 8.

A contact form is inserted into my node as a field. It is used on each node to receive mail from users. But I need to specify what node the email was sent with.

I use MYMODULE\_mail\_alter to format mail message. How can i insert node title to mail subject and body?

Or is it possible to get node title in MYTHEME\_form\_alter ?

# Answer
The current node is available from the route match, \Drupal::routeMatch()-\>getParameter('node'). Make sure it really is an instance of NodeInterface before you continue or check the route name.

Then it's easy to use $node-\>getTitle() as the default value for the subject of the contact form. Depending on what you want to do, you can then also hide the subject field.
> 1 votes

---
Tags: 8, nodes, emails
---


# Question
Title: How to create a Category Article listing with subcategories?
I am new to drupal 7 and I want following page:

```
  Main Category

  (1) Subcategory1
    - post1
      Details
    - post 2
      Details
  (2) Subcategory2
    - post1
      Details
    - post 2
      Details

```

How can I do that? I think I can use Views but I need some further details.

# Answer
> 0 votes
Drupal Taxonomy is used to Categorize Content... Please have a look @ detailed tutorial here how to use taxonomy concept in Drupal to create categories and tag contents with categories.

You need to use views module to display the content by category.

Hope it helps.

# Answer
> 0 votes
it's a lengthy process actually.

1.create a view with the `'taxonomy vocabulary'` you need to show.

2.next add a relatioship `'Taxonomy term: content using {Vocabulary}'` this will allow you to get the content that is having the vocabulary you need.

3. next you can add a contextual `Taxonomy term: Parent term` read more How does Views contextual filters work? ( you can skip this part and see what you get first )
4. Add the 'Fields' you need to show up from the content. example you can add the `'content title. taxonomy term name, taxonomy term id'`
5. The Finaly got to `'FORMAT' | Settings` group it by your `taxonomy term name` in your fields. select 'Use rendered output to group rows'

---
Tags: 7, views
---


# Question
Title: How to display Webform label Above the field instead of Inline in Drupal 8?
In Drupal 7 it was easy to select whether I wanted the label of a field to display Above or Inline with the field. In Drupal 8 I can't seem to find this feature. I realize this can be done in CSS, but that seems like a kludgy way to do it if there is just a tickbox somewhere that I am missing.

Can anyone point me in the right direction?

# Answer
> 2 votes
Ben, Let me know you webform version I can guide where you can get that option.

As of now I am using webform version 8.x-5.0-beta15 & it seems your requirement is available in this module. Below are steps for same

1. Choose Any webform. Click on edit of that webform you will see list of fields available in that webform.
2. Select any of the field and click on edit option provided. You will see one popup is opened.
3. On that popup if you scroll down little you will find your required option. Please refer attached screenshot.

Hope this helps.. :)

---
Tags: webforms
---


# Question
Title: How to set a flag at node when user view node?
I have a content type 'page'. When a user views this node, I want a flag to be set automatically not by flage module link.

Any help?

# Answer
> 0 votes
Using the Rules module seems like a no brainer to me to get this to work, with no custom module(s) needed ...

Here is how your custom rule should look like (a kind of getting started with Rules):

* Rules Event: When viewing content.
* Rules Condition: Check the content type that matches your needs.
* Rules Action: Flag the node being viewed by the current user.

Ps: I'm assuming this is about D7.

---
Tags: nodes, users, flags
---


# Question
Title: How to create custom module for admin area in drupal 8
Sorry if this question is so basic, I'm new about drupal.

So far which I know, we can create custom module or page in drupal 8 so we can access it with http://www.oursite.com/custompage.

What I need? Is possible to create custom module or page which can show in admin area? In this case, I want to sync a lot of accounts from another system/web app to my drupal site so I don't need to create manually using "people menu" in admin area. Or is there any best way to do that?

Can anyone provide a helpful articles to accomplish this? Help would so appreciated.

# Answer
> 2 votes
> Main question is "how to have a module show up in admin area".

1. Create your custom module
2. Create your custom route in the "your\_module.routing.yml" - file

Example:

```
your_module.admin_settings:
  path: '/admin/config/your_module/import'
  defaults:
    _form: '\Drupal\your_module\Form\ImportForm'
    _title: 'Import XYZ'
  requirements:
    _permission: 'administer site configuration'

```
3. Define the link in the "your\_module.links.menu.yml" - file

Example:

```
entity.your_module.admin:
  title: 'Import XYZ'
  route_name: your_module.admin_settings
  description: 'Import XYZ'
  parent: system.admin_config_system
  weight: 100

```

... thats it! In step 3 this line is the important part:

```
parent: system.admin_config_system

```

If you need a menu entry in "structure" you can use:

```
parent: system.admin_structure

```

Just read other xyz.links.menu.yml - files to find different parent-path.

---
Tags: views, 8
---


# Question
Title: Shopping cart is not updated after add to cart when you select an attributes
In my drupal commerce I have a product type. it's name is "Cellphone"

in my product type I have a field named "color" that in field settings I have set this check box "Enable this field to function as an attribute field on Add to Cart forms." so this field is an attribute. color has two options. One is red and another is blue.

When I want to create a product display , I make two products for this product display one is blue and another is red. So in product display, visitor is able to change the product via color attribute.

Now I have made and price attribute for my products. It's name is guarantee and it includes two options. "Type A" that increases price $100 and "Type B" that increases price $200

every thing works well. in product display page and during ordering, when user set color and also set an attribute, price of product change correctly. but after click on "Add to cart" button, the new item in shopping card block doesn't have correct price (it has base price without any attribute effects) and when user press on F5 and refresh the browser page, shopping card block is corrected

do you know what is the reason and how can I solve this problem ?

# Answer
> 0 votes
Here is where I would do like the big stores, and add a separate line item (product) for the warrantee add-on where you you can have two variations of it, one for $100 add-on value, the other for $200 add-on and then in the product display page you can have a customer select which option if any to select, which will then be itemized in the cart by itself with its own description. If you want you can also have a product display page or just a page for the two to them. It would be a product type by itself, with variations as opposed to color terms describing variations of a cell phone. And it might be easier on cart space. And Warrantee variations are products that can be related by name. You end up with less sku products: The cell phone product color variations, and the Warrantee two variations.

---
Tags: commerce
---


title: drush default site alias

text:
# Question
Title: drush default site alias
Is there a way of specifying a default site alias ?

couldnt find it in drushrc example nor aliases example.

**motivation** i am sclerotic and lazy :) usually running drush from the dir where the site is, so no alias needed. Now working in a setup where i am logged in on a different server then the actual site, so i need to always provide a site alias for each command. So the usual workflow is:

```
drush wipe
oh no
drush @stage wipe

```

so i thought a default site alias would save me from those two lines :)

# Answer
> 13 votes
Drush automatically defines the alias @self to refer to the currently bootstrapped site. So, if you have identified a site via cwd (that is, `cd /path/to/sites/mysite`, where `sites/mysite` is the folder that contains settings.php), then you could run:

```
drush sa @self

```

This will tell Drush to print out a site alias for the current site. You can then copy this to an alias file and give it a handy name for later use. If you're doing this for a remote site, try adding --with-db if you'd like to include the database record inside the site alias. You're better off leaving out the database information for local sites, though, as you can get inconsistent results if the db info in your alias does not match the db info in settings.php.

If you want to disable cwd-based site selection, then define 'root' and 'uri' in any drushrc.php file:

```
$options['root'] = '/path/to/drupal';
$options['uri'] = 'http://mysite.org';

```

There is no way to specify an alias in a Drush configuration file, but you could use the `site-set` command from the command line:

```
$ drush site-set @stage

```

If you wanted this command to be persistent, you could run it from your .bashrc.

# Answer
> 2 votes
It is also possible to set default uri in settings.php inside the root of your drupal folder.

Like this:

```
$base_url = 'http://localhost/...';

```

Then you don't need to update your drushrc.php file every time you start a new project.

---
Tags: drush
---


title: How do I create custom webform element?

text:
# Question
Title: How do I create custom webform element?
How can we create a custom element type in Drupal 8 webform module?

# Answer
There are many example module in the webform module itself, and three examples of custom elements all quite clear and detailed:

* **Composite element** \- webform/modules/webform\_example\_composite
* **Element** \- webform/modules/webform\_example\_element
* **Handler** \- webform/modules/webform\_example\_remote\_post
* **Config examples** \- webform/modules/webform\_examples (pre-built forms)

Using the example module makes it all simple, in this case you are extending the class `WebformCompositeBase` to implement your own composite element.
> 6 votes

---
Tags: 8, webforms
---


# Question
Title: Set value to Field collection item link field
I have a Field Collection item which consist of a drop down, a text box and a link field. After the user submits a form I create a node were this field collection item is included. Before I save it, I populate some fields.

I managed to set the 'Url' in the link field(part of field collection item) by using:

```
$field_collection_item2->field_url->setValue($base_url . '/form/email-project-completion-survey');

```

Which works fine. Now I'm trying to set the 'Link text' but I can't make it work.

Any idea?

Thank you in advance

# Answer
I managed to solve it by using an array in setValue.

```
$field_collection_item2->field_url->setValue(array('uri'=>$base_url . '/form/email-project-completion-survey', 'title' => 'Survey'));

```
> 1 votes

---
Tags: 8, entities
---


title: Depending field

text:
# Question
Title: Depending field
So i'm just begining to create a site in my company. the purpose of this internal website is to reference all setup we have in the company and i have to do it **on drupal 8**.

In order to do this i am creating a content type where i set all the field required. But i would like to have a specifique field for the screens of company users, because everyone can have 1, or even 3 screen to work here.

That's why i try to create a field "screen" which contain other fields like "serial number", "constructor", "user name" etc... but i would like to have this for each screen.

> So if a user have 3 screen he should be able to have 3 fieds "screen"

but i do not find the way to do it ... someone can bring me a piece of solution please ?

# Answer
If I understand your question correctly, the Field collection module offers the functionality you need:

> Provides a field-collection field, to which any number of fields can be attached.

However, on the Field collection page it is stated:

> Paragraphs is likely to replace field collection for Drupal 8. Field collection is on its way to being deprecated. It is recommended to use paragraphs instead of field collection for Drupal 8 projects.

I would recommend to check out the Paragraphs module, so that the content editor on your site is able to provide the different content (i.e., serial number, constructor, user name, etc.) per screen.
> 1 votes

---
Tags: nodes, entities, configuration
---


# Question
Title: how to test if a node is flagged in twig
I would like to know how to test if a node is flagged.

In D7 : if ($ flag-\> is\_flagged ($ node-\> nid)) But I discover D8 and I do not see how to do it with twig

thank you in advance

# Answer
> 0 votes
Write a function with hook preprocess\_node in your custom module and set a custom variable isflagged ture or false then check this variable in your twig file node is flagged or not like

```
/**
 * Implements hook_preprocess_node().
 */
function yourModuleName_preprocess_node(&$variables) {
  $node = $variables['node']; // Just in case you need it

  if($variables['node']->getType() == "yourNodeType") {
    // your code
    if ($flag->is_flagged ($node->id())){
      $variables['isFlagged'] = true;
    }else{
      $variables['isFlagged'] = false;
    }

  }
}

```

now in your twig

```
{% if  isFlagged %}
  //do some thing
{% endif %}

```

hope this helps you

---
Tags: 8
---


# Question
Title: Implement hook_token_info and hook_tokens
I am trying to create custom tokens, but my implementation doesn't work. I have implemented `hook_token_info()` and `hook_tokens()` like this in my `.theme` file for Drupal 7.

```
/**
* Implements hook_token_info().
*/
function THEMENAME_token_info() {
  $info = array();

  $info['types'] = array(
    'commerce-order:commerce-customer-billing' => array(
      'name' => t('Commerce Order Billing'),
      'description' => t('Global commerce order billing tokens'),
     ),
  );
  $info['tokens'] = array(
    'commerce-order:commerce-customer-billing' => array(
      'address-info' => array(
        'name' => t('Commerce address information'),
        'description' => t('Token for commerce address information'),
      ),
    ),
  );
  return $info;
}

/**
*
* Implements hook_tokens().
*/
function THEMENAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'commerce-order:commerce-customer-billing') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
      case 'address-info':
        $address_info = theme('nr_commerce_address_information', array('order' => $order));
        $replacements[$original] = $address_info;
        break;
      }
    }
  }
}

```

When I see the list of available tokens in the interface, my tokens does not show up. Why? Is there anything wrong in my code, or is the reason another one?

# Answer
I found out. It was because I tried to implement hooks in my template rather than doing it in my module.
> 2 votes

---
Tags: 7, hooks, tokens
---


title: Set term tid programmatically

text:
# Question
Title: Set term tid programmatically
I've a csv with taxonomy terms, with tids. I've to import, with a module, these terms in a new drupal installation, but if I try to set the tid programmatically, the module does not create the term. Instead, if I don't set the tid, the term is created with but with the autoincremental tid. This code doesn't work:

```
$term = new stdClass();
$term->name = 'Test';
$term->vid = 3;
$term->tid = 10; // if I remove this line the term is created
taxonomy_term_save($term);

```

The doc says: tid: (optional) The unique ID for the term being saved. If $term-\>tid is empty or omitted, a new term will be inserted.

Is there a way to set the tid programmatically? Or is there a module that do this?

# Answer
If you set `$term->tid` for a taxonomy term you save with taxonomy\_term\_save(), the function will take you are updating an existing taxonomy term, with the consequence that the taxonomy term is not saved.

You could change the taxonomy term ID for the taxonomy term you right saved, but there is the risk of conflict with an existing taxonomy term you didn't import. You should change more that one database table, and you should let other modules handling data related to taxonomy terms know they need to update their data, which means you probably should make those modules think a taxonomy term is deleted, and a new taxonomy term is created. See also the code for taxonomy\_term\_delete() to understand what Drupal does when a taxonomy term is deleted.

If you really need to export taxonomy terms from a site, and import them in a different Drupal site, you should be interested to the Universally Unique Identifier module. In that way, the taxonomy term exported from site A, and imported in site B will have the same UUID.
In Drupal 8, any entity defined from Drupal has a UUID. The schema definition used for taxonomy terms in Drupal 8, for example, is the following one.

```
  $schema['taxonomy_term_data'] = array(
    'description' => 'Stores term information.',
    'fields' => array(
      'tid' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique term ID.',
      ),
      'uuid' => array(
        'description' => 'Unique Key: Universally unique identifier for this entity.',
        'type' => 'varchar',
        'length' => 128,
        'not null' => FALSE,
      ),
      'vid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {taxonomy_vocabulary}.vid of the vocabulary to which the term is assigned.',
      ),
      // …
    ),
    // …
  );

```
> 2 votes

# Answer
A possible answer to this is that the terms added with a set is is conflicting with a previous tid. Tids numbering are not vocabulary specific. If another vocabulary is already using a tid you are trying to add, there will be conflict.

Th code you are using is in itself correct, but make sure you don't get any possible duplicates.
> 0 votes

# Answer
There is a related issue on Drupal.org.

You can parch the Drupal core with the mentioned fix.

Afterwards you can use the nex code:

```
  $name = 'TERM NAME';
  $tid = 123;
  $vocabulary_name = 'tags';

  if (!taxonomy_term_load($tid) && taxonomy_get_term_by_name($name)) {
    $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);

    $new_term = entity_create('taxonomy_term', array(
      'name' => $name,
      'tid' => $tid,
      'is_new' => TRUE,
      'vid' => $vocabulary->vid,
      'description' => ''
    ));
    taxonomy_term_save($new_term);
  }

```
> 0 votes

---
Tags: taxonomy-terms
---


title: Video Embed in FieldFormatter

text:
# Question
Title: Video Embed in FieldFormatter
I want to embed the video as follows. I have written a FieldFormatter for this.

```
public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
      // Render each element as markup.
        $target_id = $item->getValue()['target_id'];

        $file = \Drupal\file\Entity\File::load($target_id); //load the file and its attribute.
        $parts = pathinfo($file->getFileUri());
        $new_filename = $parts['filename'] . '_' . $file->getCreatedTime() .'_selfhelpvideofid_' . $target_id . '.' . $parts['extension'];

        $video = '<video width="480" height="320" controls="controls">
                    <source src="movie.mp4"  type="video/mp4">
                  </video>';

      $element[$delta] = [
        '#type' => 'markup',
        '#markup' => $video,
      ];
    }

    return $element;
  }

```

The above is not working. Please help.

# Answer
> 1 votes
Instead of #markup, which is filtered, use inline template:

```
$file_path = 'movie.mp4'

$video = '<video width="480" height="320" controls="controls">
  <source src="{{ file_path }}"  type="video/mp4">
</video>';

$element[$delta] = array(
  '#type' => 'inline_template',
  '#template' => $video,
  '#context' => array(
    'file_path' => $file_path,
  ),
);

```

---
Tags: 8, nodes, entities
---


# Question
Title: Custom Submit Handler issue in getting file
I have the following custom submit handler.

```
function example_form_submit(&$form, FormStateInterface $form_state) {
    $file = file_load($form_state['values']['file_fid']);//This works in 7
}

```

Now I want to have uploaded file information like fid, name etc. in D8. I am not able to get that.

**UPDATE:** I have also tried using the following code from here but no luck.

```
if ($form_state->hasFileElement())
{
  drupal_set_message("This form has a file element.");
  $video_file_file_array = $form_state->getValue('video_file');
  if (is_array($video_file_file_array))
  {
    if (isset($video_file_file_array[0]))
    {
      $video_file_file_id = $video_file_file_array[0];
      $file = \Drupal\file\Entity\File::load($video_file_file_id);
      if ($file != NULL)
      {
        $filename = $file->getFilename();
        drupal_set_message('Filename: ' . $filename);
      }
    }
  }
}

```

# Answer
You need to use following code to get it

```
$target_id =$form_state->getValue('field_name');//get the target_id from it
    $file = \Drupal\file\Entity\File::load($target_id); //load the file and its attribute.
            $file_image= '<img src = "' . \Drupal\image\Entity\ImageStyle::load('large')->buildUrl($file->getFileUri()) . '" />';//load the large image

```
> 1 votes

# Answer
For filename you can use getFilename()

```
$file->getFilename()

```
> 0 votes

---
Tags: forms
---


# Question
Title: How to access commerce_product field of line-items using Rules to flag the Commerce Product?
Related to this question: How to mark product if it has already been purchased by current user?

I have a Drupal Commerce shop, where I'm trying to use the Flag module to mark products to inform users if they have already purchased that particular product.

Now I'm trying to create a rule (using Rules) triggered on "Completing the checkout process" to flag all products that were purchased. Problem is I can't gain access to the `commerce_product` field (product reference field) of the line item, no matter what I do, and because of that I can't find the info I need to flag the products.

Could someone show how to do this in detail, preferably with example(s)?

# Answer
> 3 votes
Below is a possible approach you can use to solve your question. It provides the details about how I was able to have a set of Drupal messages being shown at checkout time, which look similar to this testcase I used (for a cart with 3 line items):

```
Current line item has label 'USB-BLU-08' and id '17'
Some details about this product: Product ID = 28, Product SKU = USB-BLU-08, Product Title = Storage 1, Product Creator = Hillary.Trump

Current line item has label 'TSH4-BLK-MD' and id '18'
Some details about this product: Product ID = 53, Product SKU = TSH4-BLK-MD, Product Title = Tshirt 4, Product Creator = Donald.Clinton

Current line item has label 'MES1-BLU-OS' and id '19'
Some details about this product: Product ID = 2, Product SKU = MES1-BLU-OS, Product Title = Messenger Bag 1, Product Creator = Pierre.Vriens

```

To get this to work, I created a custom rule, which also performs a custom Rules Component. Read on for details about them ...

### Step 1: Create a Rules Component

Create a Rules Component which looks like so (use the Rules UI to import it in your own site):

```
{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

```

Some details about it:

* Parameters: `selected_line_item` ( = the line item being processed).
* Rules Condition: entity (= selected-line-item) has field (= `commerce_product`).
* Rules Actions:
    + Fetch entity (= `commerce_product`) by ID (= `selected-line-item:commerce-product:product-id`).
    + Show a Drupal message, starting with "Some details about this product ..." (feel free to remove this Rules Action after you finish QA-testing).

### Step 2: Create a rule that invokes the Rules Component from Step 1

Create a rule which looks like so (use the Rules UI to import it in your own site):

```
{ "rules_access_product_fields_at_checkout" : {
    "LABEL" : "Access product fields at checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_item" : "Current line item" },
          "DO" : [
            { "drupal_message" : { "message" : "Current line item has label \u0027[line-item:line-item-label]\u0027 and id \u0027[line-item:line-item-id]\u0027" } },
            { "component_rules_perform_an_action_on_a_selected_line_item" : { "selected_line_item" : [ "line-item" ] } }
          ]
        }
      }
    ]
  }
}

```

Some details about it:

* Rules Event: After completing the checkout process.
* Rules Condition: none.
* Rules Action: Create a loop, to iterate over each line item. And for each line item, perform these Rules Actions:
    + Show a Drupal message, starting with "Current line item has ..." (feel free to remove this Rules Action after you finish QA-testing).
    + Perform the Rules Component from Step 1 for the current line item being processed.

### Step 3: Homework (= your turn)

To actually answer your question, i.e. to flag the product of each line item, you should ***only*** adapt the Rules Action in the Rules Component from Step 1. Since you have all data from each line item available at that point, it should be straight forward to tune the Rules Component to fit your needs (i.e flag the product by the current user).

---
Tags: 7, commerce, rules, flags
---


# Question
Title: Removing dozens of Routes from a collection
I am using a contrib module that is adding a local task to all entities, where I only want it to be added for Nodes.

So far, I have this written to handle the problem in the short term:

```
/**
 * Implements hook_local_tasks_alter().
 */
function mymodule_local_tasks_alter(&$local_tasks) {
  foreach ($local_tasks as $key => $task) {
    if (preg_match('/access_by_entity/', $key) && $key != 'access_by_entity.entities:node.access_tab') {
      unset($local_tasks[$key]);
    }
  }
}

```

Is there a better way to do this? Is this performant? I would rather just not have the routes exist at all, *except* for this one instance.

# Answer
> 1 votes
I think the way you're doing it is fine, although you could probably add a patch to the original module that adds the option of which entities to affect, so that instead of them being added and removed, it would only add them for the entity types you select.

Ah, I see you've already thought of this!

---
Tags: 8, routes
---


# Question
Title: What are the main difference between panels and paragraphs?
What are the main difference between the Panels and Paragraphs module in Drupal 8?

As far as I know both of the modules can be used for creating landing pages.

When to use paragraph and when to user panels?

# Answer
> 5 votes
They are not the same and you can't do the same thing with them.

Panels

> The Panels module allows a site administrator to create customized layouts for multiple uses.

Paragraphs

> Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's.

With Paragraphs you can create collections of items, like you can do with Field collection, as they are fields that you can attach to your content types, you can't do this with Panels.

In the other hand if you want to modify your layout in a simple and easy way you can use Panels, and if you have a collection of items maybe you have used Paragraphs in the content that you're showing.

---
Tags: theming, 8, panels, paragraphs
---


# Question
Title: How to show a list of students: pairing entity references?
I'm working on a drupal page for an academic department, and I've created content types for Faculty, Students and Alumni. Both the Student and Alumni content types have a field for "Advisor", which is an entity reference to a Faculty member. In the student and alumni display, the advisor field then links to the advisor's page.

Now, I'd like to have the advisor page show a list of all their students (current and former). Is there a simple module that will do this? I don't want to write my own module - if there isn't a relatively simple way to do it, I can just have an entity reference in the Faculty content type and do manual entry.

# Answer
> 1 votes
EVA: Entity Views Attachment can help you doing this task.

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

See this tutorial: https://www.torontowebsitedeveloper.com/drupal-video-tutorials/drupal-7-node-reference-tutorial

"Entity Views Attach: Use Views Almost Anywhere" contains a great tutorial about it.

---
Tags: entities
---


# Question
Title: Share nodes and users across multiple sites
I understand sharing databases/tables is frowned upon as a practice, however, I need to share users and some nodes between two websites. What are the alternatives and what are the pros and cons of the most common strategies?

To give slightly more detail. I need to create a website for "staff and authenticated users" that is separate to a main site that the public anonymously accesses. On this secondary site there will be forums and chat functionality moderated by admins for both sites. I would like to avoid having the admin users re-log in when they are managing the second site.

I also need to allow for some future integration where some "logged in" user content appears on the main site.

Are the two alternatives for doing this only,

* Make one giant single site
* Share databases

or is there some other way?

# Answer
> 2 votes
Sharing users can be done by setting up OpenAuth or something like it.

Sharing nodes can be done using views database connector this tool will let you pull data from a table in another database. To make it work for pulling in nodes, create a MYSQL view (https://dev.mysql.com/doc/refman/5.7/en/create-view.html) that holds the node data you need to share out. The views connector will be able to read in that table allowing you to create views from your other server without having to duplicate the content. You can filter on any field in the table. This set up works well for a 1 to Many Content server environment where you don't want to have a new copy of every node on every new install. https://www.drupal.org/project/views\_database\_connector

You can also create a module that pulls data from the other database and present it any way you want.

If you are fine duplicating the content you may want to explore Drupal aggregation it's easy to set up and can all be done through the UI.

---
Tags: 8, users, multi-sites, domain-access
---


# Question
Title: DrupalCommerce: Alter rates retrieved from Fedex/UPS
Is it possible to alter the rates retrieved by commerce\_fedex/commerce\_ups modules? The actual functions to retrieve rates from an API are being called by a rule:

* `commerce_fedex_service_rate_order`
* `commerce_ups_service_rate_order`

There doesn't seem to be a hook to alter the result of that function.

# Answer
In the order of my searches,

1. There is a hook after all, to alter the result of that function, I used a Google search the terms "commerce\_ups\_service\_rate\_order alter" and it returned https://www.drupal.org/node/1357492: Where it was pronounced fixed for the 7 version.
2. Searching my local site for "hook\_commerce\_shipping\_service\_rate\_options\_alter" with UPS module only installed, (Not Fedex too) yields 5 responses in 5 files in two folders, files result of this localized search for that:

* commerce\_shipping/commerce\_shipping.api.php
    * commerce\_ups/commerce\_ups.module
    * commerce\_deploy/commerce\_deploy\_shipping/commerce\_deploy\_shipping.module
    * commerce\_shipping/commerce\_shipping.api.php
    * commerce\_ups/commerce\_ups.module

I hope my search results have answered your question as seeming not be a hook for the functions.
> 0 votes

---
Tags: commerce
---


# Question
Title: Why the commit is not shown in the issue after it is closed as fixed?
Yesterday I saw that I forget to commit a change in a 8.x branch of a project, so I search for the commit message in the 7.x branch and I commit the changes and push my code to drupal.org, but today I see that the commit appears in the project page but not in the issue.

If you go to see the commit you will see the issue number and reference:

https://www.drupal.org/commitlog/commit/43654/082f754b0f3780979663afea014df3cb84d0eeec

> Issue #2846726 by ...

But in the issue page the commit not appears, this can be because the issue have the *Closed (fixed)* status?

# Answer
It is more likely the case that the service that handles the issue updates was down for some period of time. Under normal circumstances pushing a commit to D.O. will update the issue referenced in the commit message no matter what the issue status is set to...
> 4 votes

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


# Question
Title: How to add a Custom Operation in the Book Admin Edit Form's Operations?
As the title says I want to know how to add a ***custom operation*** in the drupal 8 ***book admin edit form's operations***. I need this for my module in which I want to provide ***Add Sub Page*** operation for the user.

Upon clicking on the operation, I want to execute a function to add a new page to the parent page. I know how to add pages programmatically (***Thanks to Lisa*** regarding help for adding pages in the book) , the only thing that I need is this operation entry in the drop down list.

Can somebody please help?

# Answer
You can override the bookAdminTableTree() method in the BookAdminEditForm class by extending core/modules/book/src/Form/BookAdminEditForm.php with your own custom form class. You can copy the bookAdminTableTree() method's code and then add an item to the $form\[$id\]\['operations'\]\['#links'\] array for 'add-sub-page' (or whatever you want to name the new operation.)

Then alter the existing /admin/structure/book/{node} route (book.admin\_edit) in book.routing.yml with a route to your new custom form class. See www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones and the setDefault() method in the Route class: api.drupal.org/api/drupal/vendor%21symfony%21routing%21Route.php/class/Route/8.2.x

This is a helpful tutorial that describes the overall approach: https://www.jaypan.com/tutorial/drupal-8-extending-core-configuration-extending-core-forms-and-overriding-core-routes
> 0 votes

---
Tags: 8, nodes, entities
---


# Question
Title: BaseFieldDefinition change DB column type
In a content entity definition, I've got the following:

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields = parent::baseFieldDefinitions($entity_type);

  $fields['frames'] = BaseFieldDefinition::create('string')
    ->setLabel(t('Frames'))
  ->setDescription('A serialized representation of the given frames');

  return $fields;
}

```

This is creating the column type in the database as varchar, with a maxlength of 255. I need the column to be type text, as the length will be unknown, and often more than 255. Does anybody know how to create a BaseFieldDefinition that becomes type 'text' in the database when the content entity is enabled?

# Answer
> 1 votes
`BaseFieldDefinition::create('string_long')` creates a LONGTEXT database column without the extra *\_format* column.

---
Tags: 8, entities, database
---


title: File (Field) Paths get year only

text:
# Question
Title: File (Field) Paths get year only
I've recently found and started using the File Fields Path module in Drupal 7 and I have a date field that I'm only collecting the year from. Using that in the file path part of the module, it returns the value as YYYY-MM-DD-HHMMSS.

So a value of 2017 shows up as 2017-01-01-000000 since I didn't collect any of the other information.

Is there a way to just get it to make the folder as 2017 instead of the whole date?

Thanks for any help!

# Answer
> 0 votes
You should be able to go to the manage fields area for that field - something like admin/structure/types/manage/article/fields/field\_field\_path

and for the "file path" setting, enter \[current-date:custom:Y\].

This is untested, but *should* work. Get back to me if it doesn't.

---
Tags: 7, files
---


title: How to load jQuery from a module

text:
# Question
Title: How to load jQuery from a module
Drupal 7.x, Garland theme.

I am writing a module that depends on jQuery. I am seeing that when an anonymous visitor comes by that jQuery isn't being loaded. How do I load jQuery from my module?

I am not really a Drupal developer. This is my first module. I want to maintain Core as is (no hacking) for easy updates and I don't want to change themes from Garland, so I don't really want to edit the theme to force jQuery.

Thanks.

# Answer
See Added methods to avoid loading jQuery and related JavaScript libraries on all pages when they are not needed.

Starting from Drupal 7.36, Drupal could not load jQuery to the page.

If you are adding JavaScript from your module, it means you are doing one of the following:

In both the cases, you can force Drupal to load jQuery.

```
drupal_add_js('path/to/some/javascript-library-needing-jquery.js', array('requires_jquery' => TRUE));

```

```
$build['#attached']['js'][] = array(
  drupal_get_path('module', 'mymodule') . '/javascript-library-needing-jquery.js' => array('requires_jquery' => TRUE)
);

```

Notice that, normally, calling `drupal_add_js()` or adding `$build['#attached']['js']` is sufficient for making Drupal load jQuery, but if another module set `'requires_jquery'` to `FALSE`, or if the settings.php file contains a `$conf['javascript_always_use_jquery'] = FALSE;` line, then jQuery will not be loaded. Only when your module is setting `'requires_jquery'` to `TRUE` with one of the methods I described, you are sure the jQuery library is loaded from Drupal.

Notice that, in either cases, if none of the modules (or the theme) is adding JavaScript code to the page through `drupal_add_js()`, `#attached`, or the *scripts* directive in a .info file, Drupal will not load the jQuery library. This means that, if you are hard-coding the link to an external JavaScript file in a template file, Drupal will not know JavaScript code is being used, and it will not load the jQuery library found in the *misc* directory of the Drupal root directory.
> 0 votes

# Answer
jQuery should be available to you right out of the box in D7 if I remember correctly. But you need to use `jQuery(...)` instead of `$(...)`. If jQuery is not being included for some reason, try using drupal\_add\_js().

See Drupal 7 JavaScript API documentation for more information.
> 0 votes

---
Tags: javascript
---


# Question
Title: How do I restrict a user from edit his/her own profile
I have some custom fields added to the user profile. some of these fields are filled and synced autimatically from an LDAP account and others only admins can fill. I want to keep these aditional fields on the profile page but don't want to let the user itself modify these. how can I restrict a user from edit his/her own profile?

# Answer
> 2 votes
You can either hide them from the form on the Manage Form tab, or use a form alter hook to set `#access` to FALSE if they don't fit a certain role.

You can also try the Field Permissions module.

---
Tags: 8
---