# Question
Title: how to get list of all route in routeProvider?
I have:

```
class MyRouteProvider extends DefaultHtmlRouteProvider {
    public function getRoutes(EntityTypeInterface $entity_type) {
        $test = parent::getRoutes($entity_type); // TODO: Change the autogenerated stub
        // how do i get list of route that i have in this method?
    }
}

```

how do i get list of route that i have in getRoutes method?

what i'm trying to do here is: I like to search a particular route (based on $entity type) that created by my\_entitiy and modify it.

# Answer
> 2 votes
Not really sure what you are aiming for, but you have it already as the `getRoutes()` method works with a Symfony `RouteCollection` collection

```
class MyRouteProvider extends DefaultHtmlRouteProvider {
  public function getRoutes(EntityTypeInterface $entity_type) {
    /** @var \Symfony\Component\Routing\RouteCollection */
    $collection = parent::getRoutes($entity_type);
    /** @var \Symfony\Component\Routing\Route[] */
    $routes = $collection->all();

    return $collection;
  }
}

```

If sounds like, though, you want to implement a `RouteSubscriber` to alter the route. There are a bunch of these in core to use as examples. And you don't need to get all of the routes, and then search through them. You can just use the route collection and get the route that you need. The route subscriber defined by the Node module is probably the simplest example:

```
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // As nodes are the primary type of content, the node listing should be
    // easily available. In order to do that, override admin/content to show
    // a node listing instead of the path's child links.
    $route = $collection->get('system.admin_content');
    if ($route) {
      $route->setDefaults([
        '_title' => 'Content',
        '_entity_list' => 'node',
      ]);
      $route->setRequirements([
        '_permission' => 'access content overview',
      ]);
    }
  }

}

```

Note that is just does a `$collection->get()` to find a particular route, and then modifies it.

---
Tags: 8, routes
---


title: Mobile number validation for webforms

text:
# Question
Title: Mobile number validation for webforms
I am looking for a way to easily implement an Integer field with webforms that can do mobile number validation (US numbers only). I am aware of http://drupal.org/project/webform\_validation that can do numeric validation but looking for a more direct solution. If its a hook, that works as well.

# Answer
> 2 votes
You can do a hook\_form\_alter of your form, and add your own validation to it.

```
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'NAME_OF_FORM') {
    $form['#validate'][] = 'YOURMODULE_VALIDATE_FUNCTION';
  }
}

function YOURMODULE_VALIDATE_FUNCTION( $form, &$form_state ) {
  $mobile = $form_state['input']['field_MOBILE']['und'][0]['value'];
  $is_valid_mobile = YOUR_AWESOME_MOBILE_VALIDATOR($mobile);
  if( !$is_valid_mobile ) {
    $error_msg = 'Mobile is invalid. Please enter a valid mobile number e.g xxx-yyy.';
    form_set_error('field_MOBILE', t($error_msg));
    return false;
  }
}

```

# Answer
> 1 votes
Telephone numbers are not integers. For example they begin with a zero in Germany, which is meaningless for integers but significant when dialing. A string field would be more appropriate.

You will also have to think about what quality of validation you need:

1. The number looks like a telephone number
2. The number looks like a telephone number that belongs to a cellphone
3. The number is currently assigned to a cellphone.

In all cases, the way to go is a validation function as per Danno's suggestion. For 2, you need information from the ITU and its members. For 3, sending an SMS with a validation code is probably the most effective way (although some landline phones can receive SMS).

# Answer
> 0 votes
Mobile number module (that I wrote) supports webforms and has a component for validating mobile numbers of any country. It is based on the libphonenumber composer library.

> Mobile Number is a field type that provides mobile number validation and verification, and can be used for two factor authentication.

---
Tags: webforms
---


title: SMS for login to website

text:
# Question
Title: SMS for login to website
Is there any way for sending code by SMS when the user login to the website "OTP", I want my website more security for login, the users have to type Username,password, SMS code.

Thanks for your support,

# Answer
You Can go for Twilio Module

```
The Twilio module provides integration with the Twilio cloud communication platform
allowing for your Drupal site to integration Voice and SMS functionality.

```

What you can do using this module

```
Ability to store and access TwiML
Rules event to act on incoming SMS message
Rules action to send an SMS message
Rules event to execute TwiML scripts
Hook for incoming SMS messages
Hook for incoming voice calls
User object phone number storage and validation
Uses libraries api to manage the Twilio php library
Support for international texting
Support for MMS

```
> 1 votes

# Answer
You can try the OTP Verification module.

> For module documentation,
>
> Verify your user's email address or mobile number during registration or landing page form submission with One Time Passcode(OTP).
>
> OTP Verification module verifies Email Address/Mobile Number of users by sending verification code(OTP) during registration. It removes the possibility of a user registering with fake Email Address/Mobile Number. This module checks the existence of the Email Address/Mobile Number and the ability of a user to access that Email Address/Mobile Number.
> 1 votes

# Answer
What about using the Google Authenticator module? Many sites use the App to provide two factor authentication (OTP) including Dropbox and Github. I'm not sure on whether that natively falls back to SMS but perhaps it's a good place to start.

https://www.drupal.org/project/ga\_login

Actually here is a Two Factor Authentication framework solution that provides a pluggable API solution with SMS and Authenticator in a companion module. SMS in that module is provided by Twilo

API module https://www.drupal.org/project/tfa

Companion https://www.drupal.org/project/tfa\_basic
> 0 votes

# Answer
You can try Mobile number module, that I wrote. Works with SMSFramework for sending SMS and TFA for adding second factor authentication to login. It comes with mobile number validation and verification to boot.
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: Cell Phone Validation field using sms message
I recently want to develop a field for user account.

The Field will provide a cellphone textfield and a validate button!

After finishing the cellphone textfield by the user, The user push the validate button. Then, the system will send the sms message using ajax.

After sending the validate code message to the user, the system will respond the CODE to the client side. However, the cell phone textfield is invisible right now.

Finally,the user enter the code get from sms message and then push the button.

The system will check the code by ajax and then return the correct/false value to the client side.

After the steps above, the system will hide all the field and show the result of the validation.

My question is how can I do that?

# Answer
You don't want to create this yourself. You want to use the relatively new Two-Factor Authentication Module and it's plugins -- or create your own plugin.

> Second-factor authentication for Drupal sites. Drupal provides authentication via something you know -- a username and password while TFA module adds a second step of authentication with a check for something you have -- such as a code sent to (or generated by) your mobile phone.
>
> TFA is a base module for providing two-factor authentication for your Drupal site. As a base module, TFA handles the work of integrating with Drupal, providing flexible and well tested interfaces to enable your choice of various two-factor authentication solutions like Time-based One Time Passwords (TOTP), SMS-delivered codes, pre-generated codes, or integrations with third-party services like Authy, Duo and others.
>
> Features
>
> * Pluggable - Supports multiple methods of 2nd factor verification and can work with any number of 3rd party systems
> * Configurable - Supports fallback methods and context-specific exceptions
> * Flood control and even secures one-time logins
> * **Tested - Over 100 tests**
>
> TFA module is recommended as a full suite solution to 2nd factor authentication and Drupal.
>
> See the TFA basic plugins for a TOTP plugin that works with FreeOTP, Google Authenticator, Authy, and any other app that works with TOTP tokens.
>
> This module stores some sensitive data which it encrypts using the php mcrypt library. You will need to have the mcrypt extension installed to use the module.

This module is designed to allow you to meet your use-case (some custom code may be required). It's also designed with *fallbacks* and edge-cases taken into consideration which you may not have thought of -- and it has a zillion tests.
> 1 votes

# Answer
Mobile Number module (that I wrote) does exactly that.

> Mobile Number is a field type that provides mobile number validation and verification, and can be used for two factor authentication. It works with SMS Framework and TFA modules, respectively, and both features are optional.
>
> The module differs from the Phone module in that it puts security and authenticity first, and focuses on mobile numbers which therefore assumes sms and smartphone capabilities by the user.
> 1 votes

---
Tags: forms
---


# Question
Title: How can I attach a phone number field to the user account and optionally validate it via SMS?
On my site, after registering their account, I want users to optionally be able to go to their account page, input a phone number, and then verify that number by SMS. When they verify the phone number, I want to award a special role (ideally via Rules).

It seems like there are several modules that might be able to do this:

* Two-factor authentication-- this supports SMS with the TFA Basic plugins, but I don't want to use SMS for authentication, just once to verify the number.
* Twilio-- this module has user phone number verification, but it does it in a special database table (not a Drupal field) and does not have a rules event for "when a number is verified."
* SMS Framework-- this module contains a submodule ("SMS Framework Users") for phone number verification, but it only works on registration; there is no option to register a number later (and in my case, I do not want to collect numbers on registration; I want to collect numbers later optionally).

Related questions:

# Answer
> 1 votes
To address the modules mentioned:

1. This is a non-starter as it's a different use case from SMS number verification.
2. Here you'd have to build off the back the Twilio module. You could modify user setting form `twilio_user_settings_form()` so that the callback `twilio_user_settings_confirm_form_submit()` is altered with your own custom callback that triggers a callback. Alternatively, you could evoke a `hook_user_presave()` as `twilio_user_settings_confirm_form_submit` calls `user_save()` with `'status' => TWILIO_USER_CONFIRMED`, in the `$edit` array. In either case, you'd have to build/evoke your own custom rules event.
3. The *SMS User* module does provide verification for existing users. The form can be found under the path **user/{UID}/edit/mobile**. It triggers *User validated SMS code* event once the user has completed the verification process.

Given the above, both modules can achieve what you're looking for, it's just a matter of how much modification vs. what each service provides (Twilio vs. any other SMS Gateway provider).

# Answer
> 1 votes
I managed to do this with the Twilio module.

1. First I applied a patch to get the "when a number is verified" rules event.
2. The path for Twilio phone number verification is **/user/UID/edit/twilio**.
3. The text strings in this module required heavy revision (English not quite accurate, lack of punctuation, etc.)

I then used Rules, Panels, Flag, and other modules to make a custom flow in which users are prompted to verify by SMS after registration.

# Answer
> 0 votes
You can do this with the Mobile Number module that I wrote. And using rules you can check the number was verified.

> Mobile Number is a field type that provides mobile number validation and verification, and can be used for two factor authentication. It works with SMS Framework and TFA modules, respectively, and both features are optional.

---
Tags: users, forms
---


title: Views JSON entity reference fields

text:
# Question
Title: Views JSON entity reference fields
I have a **page** content type with fields **Title**, **Body** and **Blocks** field collection with fields **Title** and **URL**.

It might be **field collection**, **paragraphs** or **entity reference**, it doesn't matter because all of these types require relationship in views in order to get its fields.

I need to generate a JSON output with views that look like this:

```
{
  'title': 'This is my title',
  'body': '<p>lorem ipsum dolor sit amet.</p>',
  'blocks': [
    {
      'block_title': 'Block one',
      'block_url': 'www.example.com'
    },
    {
      'block_title': 'Block two',
      'block_url': 'www.site.com'
    },
  ]
}

```

What I managed to achieve so far, is this:

```
[
  {
    'title': 'This is my title',
    'body': '<p>lorem ipsum dolor sit amet.</p>',
    'block_title': 'Block one',
    'block_url': 'www.example.com'
  },
  {
    'title': 'This is my title',
    'body': '<p>lorem ipsum dolor sit amet.</p>',
    'block_title': 'Block two',
    'block_url': 'www.site.com'
  }
]

```

This is Drupal 8. Any suggestions?

# Answer
> 0 votes
The data structure you want does not fit with what Views is supposed to provide. Views is intended only for generating lists. 'title' and 'body' are assumed to not be part of a list, so views has no configuration for defining single hardcoded values, and goes against how views works.

Your other option is to create a custom route with a node parameter (example) that returns a JsonResponse object with populated blocks property. So your code may look something like this (based on route parameter example above):

```
use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class ExampleController {
  function foo(NodeInterface $node) {
    $response = [
      'title' => $node->label(),
      'body' => $node->get('body')->first()->getValue(),
    ];

    $blocks = [];
    $block1 = $node->get('block')->get(0)->get('entity');

    $blocks[] = [
      'block_title' => $block1->label(),
      'block_url' => $block1->toUrl()->toString(),
    ];

    /* ... add the rest of the blocks ... */

    $response['blocks'] = $blocks;

    return new JsonResponse($response);
  }
}

```

The code will need to be adjusted according to your entity field setup.

---
Tags: views, 8
---


# Question
Title: How do I hide a local task (tab) if a module is disabled?
I would like my local tasks (tabs), defined in *mymodule.links.task.yml*, to appear only if a certain module is enabled. If a certain module is disabled, I want the tab to be hidden.

```
mymodule.alpha:
  route_name: mymodule.alpha
  base_route: mymodule.alpha
  title: 'Alpha'

mymodule.bravo:
  route_name: mymodule.bravo
  base_route: mymodule.alpha
  title: 'Bravo'

```

My understanding is that this can be acheived by adding a *\_module\_dependencies* key to my *routing.yml* file.

> \_module\_dependencies: Optionally use this key to specify one or more modules that are required to serve this path. You can combine module names with a + (plus) for an AND relationship or , (comma) for an OR relationship. For example, \_module\_dependencies: 'node + search' means both node and search are needed, \_module\_dependencies: 'node, search' means either node or search are needed. If your module already depends on other modules for its behavior (via info.yml dependencies), there is, of course, no need for specifying the dependency here as well; however, for optional dependencies, where routes are provided only if those optional dependent modules are also enabled, this is a useful option.

https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

```
mymodule.alpha:
  path: '/admin/reports/mymodule/alpha'
  defaults:
    _controller: Drupal\mymodule\Controller\AlphaController::render
    _title: 'Alpha'
  requirements:
    _permission: 'access site reports'
    _module_dependencies: 'comment' # this is module is enabled, this line does not cause a white screen on cache rebuild

mymodule.bravo:
  path: '/admin/reports/mymodule/bravo'
  defaults:
    _controller: Drupal\mymodule\Controller\BravoController::render
    _title: 'Bravo'
  requirements:
    _permission: 'access site reports'
    _module_dependencies: 'statistics' # this is module is disabled, this line does cause a white screen on cache rebuild

```

However, if a module is disabled, I get this error:

> Symfony\Component\Routing\Exception\RouteNotFoundException: Route "mymodule.bravo" does not exist. in Drupal\Core\Routing\RouteProvider-\>getRouteByName() (line 187 of /var/www/mysite/core/lib/Drupal/Core/Routing/RouteProvider.php).

The error is thrown even when I visit: */admin/reports/mymodule/alpha*.

# Answer
> 2 votes
I believe my problem was that if the module was disabled then the route would not exist - and this would have my *links.task.yml* trying to create a local task from a non existent route.

My solution was to generate a dynamic local task instead, so that the local task is only created, if the module is enabled:

*mymodule.links.task.yml*

```
mymodule.bravo:
  deriver: 'Drupal\mymodule\Plugin\Derivative\BravoLocalTasks'

```

*src/Plugin/Derivative/BravoLocalTasks.php*

```
namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

/**
 * Generates local tasks.
 */
class BravoLocalTasks extends DeriverBase {

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $moduleHandler = \Drupal::service('module_handler');
    if ($moduleHandler->moduleExists('statistics')) {
      $this->derivatives['mymodule.bravo'] = $base_plugin_definition;
      $this->derivatives['mymodule.bravo']['route_name'] = 'mymodule.bravo';
      $this->derivatives['mymodule.bravo']['base_route'] = 'mymodule.alpha';
      $this->derivatives['mymodule.bravo']['title'] = 'Bravo';
    }
    return $this->derivatives;
  }
}

```

I believe I will have to create a distinct class for every route that requires dynamic local tasks.

If you have a better solution, please post.

---
Tags: 8, routes
---


# Question
Title: How do I change template file for the user registration form?
I want to use a different template file for the registration form, but I don't want to use page--user--register.html.twig because in this case I should rewrite all the page structure. We had user-register.tpl.php in Drupal 7, but I couldn't find the theme name in Drupal 8.

# Answer
> 3 votes
I found the solution here: http://www.foreach.be/blog/how-manipulate-forms-drupal-8 and the file name for overriding the user register form is: `form--user-register-form.html.twig`

---
Tags: theming, users
---


# Question
Title: How to transfer field content of a view to a another view as a filter by clicking this content entry
Example: View 1, field "city", content "Berlin" By click on "Berlin" -\> opens View 2 (filter on "Berlin") in a separate block. Is this feasible? How do you do that?

Btw: activating the second view in a block by a click - it seems impossible, isn't? Which way: Make view per page and then -\> into a block???

# Answer
> 0 votes
```
<a href="{{ url('view.testview.page_1', {'arg_0': field_example__value}) }}">{{field_example__value}}</a>

```

view-\> Field-Content field\_example \_\> overwrite output.

Works as well. Thx to 4\*4 again.

---
Tags: views, 8
---


title: Adding a custom HTML block to a view

text:
# Question
Title: Adding a custom HTML block to a view
I have a view in Drupal 8 that looks as follows (see screenshot). To make the long story short, I need to make this view output a fixed HTML block (piece of code, not Drupal Block) and not pull any dynamic data from the respective content type.

What is the most efficient way of doing this?

# Answer
> 3 votes
In your screen shot, there is **HEADER** and **FOOTER** section. Click add in one of them and add a `Global: Text Area`, and put your HTML there, for text filter use `FULL HTML`.

# Answer
> 1 votes
Output the block to the page. View the HTML source for the page. Copy the HTML for the block.

If you want to display the block on the site, then create a new block through the admin interface, and paste the HTML there.

# Answer
> 0 votes
If it helps anyone, what i ended up doing was creating a new custom Block in Drupal and pasting the needed HTML there as Full HTML format. I then placed this new Block in place of the View in question on the needed page. I did the latter on the Block Layout page.

---
Tags: views, blocks
---


# Question
Title: How can I have different templates for newly created content?
I am using Drupal 7 and I need to show a different content for a custom entity depending on if the recently created content is being shown after submitting the form or if I visit the URL afterwards.

Is there a way to have different templates or is there a variable to check that tells you if it's newly created content?

I need this because I'm going to let the user share the page on social networks from that page, and I need to show a different content when people visit it afterwards.

# Answer
Here's one way to solve this. In a nutshell:

1. Create a custom view for your entity using Display Suite or Entity View Modes. Display Suite is preferred, as it allows you to also create custom fields and custom layouts for your entity display. This is the custom view your authors will see when they submit the entity create form.
2. Alter the entity creation form and **add** a new `submit` handler (be sure not to delete the default submit handler, as that will take care of creating and saving the entity before your custom handler is called).
3. In the new `submit` handler, create a `form_state['redirect']` to a custom menu item
4. Create a custom menu item (with `hook_menu`) that will load your entity and pass it to a page callback
5. The page callback will build and return the entity custom view you defined in step 1.

Here's the code for all this (except step 1). **PLEASE NOTE**: since I don't know what custom entity you are using, this example uses **Basic page** node (content) type. You will need to adapt to your custom entity. All this code goes in a custom module called `my_custom_view.module`.

Also note: the custom view I created in Display Suite is called `custom` (see `node_view()` in the page callback).

```
<?php

function my_custom_view_form_page_node_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'my_custom_view_form_submit';
}

function my_custom_view_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'custom-node-view/'.$form_state['nid'];
}

function my_custom_view_menu() {
  $item = array();
  $item['custom-node-view/%node'] = array(
    'page callback' => 'my_custom_view_page',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );
  return $item;
}

function my_custom_view_page($node) {
  return node_view($node, 'custom');
}

```
> 1 votes

---
Tags: theming, entities
---


# Question
Title: My Aquia Dev Desktop is insanely slow. What could be the problem?
I'm running Drupal 7 with the latest version of Aquia Dev Desktop and the site is REALLY slow on local host. I mean something like one minute to load a node to edit it, and three minutes to load the modules page.

I tried the Boost module, and I have all the performance settings maxed out. What could the problem be (a port, the PHP version, too many installs)? I have about seven sites in there.

The site on the live server (in the USA) is faster and I'm connecting from Thailand; that is twice as fast as localhost.

# Answer
> 2 votes
I experienced the same thing when I tried using the Acquia Dev Desktop.

I now use c9.io (clould 9) and do all my development in the cloud `:)`

Here is a nice overview video of the IDE.

---
Tags: database, acquia-dev-desktop
---


title: Are URLs UTF-8 encoded?

text:
# Question
Title: Are URLs UTF-8 encoded?
I want to use special characters (like üßä) in my clean URL alias's and google says they must be UTF8 encoded.

I have no idea if this is the case by default, or how to check. Are URLs UTF-8 encoded?

# Answer
> 1 votes
Everything in Drupal is UTF-8 encoded, yes.

Be aware that various tools still don't properly support such characters in URLs and might display it encoded.

---
Tags: 8, uri
---


# Question
Title: How to show picture of the user who triggered the rule for message activity?
I am using message module to record user activity on the site and displaying it through views. I am using rules module to trigger actions on certain events and show the relevant message.

How I can show picture of the user who triggered the event?

For example: When my question is liked by clive, I receive a message notification that "Clive liked your question". I only see a plain text. How to show the user picture?

# Answer
> 1 votes
Since you are using Rules to create your messages to be delivered, you can try to make the missing tokens available by using the ***Replacement patterns*** for each message type. Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that (it explains how these Replacement tokens can be used to pass data available in Rules to the Message module).

With that, your only remaining challenge is to get access to the user picture in a custom rule. In D8 that picture has become a field also, but that's not the case in D7. Therefor you may get it to work in D7 also if you also use the user picture field module (which doesn't have an official D7 release yet, but about 11K reported installs sounds like it's a pretty stable module).

---
Tags: 7, views, users, rules, message-subscribe
---


title: How does module_enable works in Drush?

text:
# Question
Title: How does module_enable works in Drush?
I'm trying to automatize an install of CiviCRM and Drupal, but I'm getting so many errors! (Using PHP 7, Drush 8, Drupal 7, CiviCRM 4.7.18)

CiviCRM has a Drush extension, which calls function `module_enable(array('civicrm'))`

However, Drush 8 (which says is compatible with D6, D7 and D8) throws `Undefined function`.

I would like to know if I should downgrade my Drush 8 or what? Can I fix this error in some way?

These are the errors I get.

```
Error: Call to undefined function module_enable() in drush_civicrm_install() (line 367 of /root/.drush/civicrm.drush.inc) #0               [error]
phar:///usr/local/bin/drush/includes/command.inc(422): drush_civicrm_install()
#1 phar:///usr/local/bin/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#2 phar:///usr/local/bin/drush/includes/command.inc(199): drush_command()
#3 phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#4 phar:///usr/local/bin/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#5 phar:///usr/local/bin/drush/includes/startup.inc(458): drush_main()
#6 phar:///usr/local/bin/drush/includes/startup.inc(365): drush_run_main(false, '/', 'Phar detected. ...')
#7 phar:///usr/local/bin/drush/drush(114): drush_startup(Array)
#8 /usr/local/bin/drush(10): require('phar:///usr/loc...')
#9 {main}.
Error: Call to undefined function module_enable() in /root/.drush/civicrm.drush.inc on line 367 #0 phar:///usr/local/bin/drush/includes/command.inc(422): drush_civicrm_install()
#1 phar:///usr/local/bin/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#2 phar:///usr/local/bin/drush/includes/command.inc(199): drush_command()
#3 phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#4 phar:///usr/local/bin/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#5 phar:///usr/local/bin/drush/includes/startup.inc(458): drush_main()
#6 phar:///usr/local/bin/drush/includes/startup.inc(365): drush_run_main(false, '/', 'Phar detected. ...')
#7 phar:///usr/local/bin/drush/drush(114): drush_startup(Array)
#8 /usr/local/bin/drush(10): require('phar:///usr/loc...')
#9 {main}
Error: Call to undefined function module_enable() in drush_civicrm_install() (line 367 of /root/.drush/civicrm.drush.inc).
Drush command terminated abnormally due to an unrecoverable error.

```

Changing it to `drush_module_enable()` ends in another error:

```
Drupal\Core\Extension\MissingDependencyException: Unable to install modules civicrm due to missing modules civicrm. in                     [error]
/opt/compucorp/core/lib/Drupal/Core/Extension/ModuleInstaller.php:85
Stack trace:
#0 /opt/compucorp/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(83): Drupal\Core\Extension\ModuleInstaller->install(Array,
true)
#1 phar:///usr/local/bin/drush/commands/core/drupal/environment.inc(131): Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array,
true)
#2 phar:///usr/local/bin/drush/commands/core/drupal/environment.inc(198): drush_module_install(Array)
#3 /root/.drush/civicrm.drush.inc(367): drush_module_enable(Array)
#4 phar:///usr/local/bin/drush/includes/command.inc(422): drush_civicrm_install()
#5 phar:///usr/local/bin/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#6 phar:///usr/local/bin/drush/includes/command.inc(199): drush_command()
#7 phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#8 phar:///usr/local/bin/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#9 phar:///usr/local/bin/drush/includes/startup.inc(458): drush_main()
#10 phar:///usr/local/bin/drush/includes/startup.inc(365): drush_run_main(false, '/', 'Phar detected. ...')
#11 phar:///usr/local/bin/drush/drush(114): drush_startup(Array)
#12 /usr/local/bin/drush(10): require('phar:///usr/loc...')
#13 {main}

```

# Answer
> 1 votes
Since the code is raising an exception like Drupal\Core\Extension\MissingDependencyException, you aren't using Drupal 7, but Drupal 8, which doesn't have a `module_enable()` function anymore.

You don't need to down-grade Drupal, but use the correct Drupal version, which in your case (since the CiviCRM Drush extension is calling `module_enable()`) is Drupal 7.

# Answer
> 1 votes
`module_enable` is a Drupal 7 function - it would seem you're not running this command on a drupal 7 site.

Downgrading Drush won't have any effect, if you want to use this extension with Drupal 8 the code will need to be updated to satisfy the new API.

The new equivalent is:

```
\Drupal::moduleHandler()->enable(['civicrm']);

```

---
Tags: drush
---


# Question
Title: How to display a block view on demand triggered by clicking content of another view?
A Link from a field value (view 1) to another view (view 2) with contextual filtering works as well, if the second view is a page view. But what about, if the second view should be a block view, only displaying after clicking on the link in view 1?

# Answer
> 1 votes
A link just takes you to a different page. Since blocks are associated to pages, you just need to link to a page to which the block is associated.

Linking to the same page that should then show the block is not possible, since blocks appear right when the page is shown. There isn't a way to delay the block appearing on pages.

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


# Question
Title: Views API custom table not showing fields
I'm creating a custom view that corresponds to my module's table.

I already called the hook\_views\_api() hook.

```
function sample_views_api() {
    return [
        'api' => 3,
        'path' => drupal_get_path('module', 'sample')
    ];
}

```

To generate the view I called the hook\_views\_default\_views() hook.

```
function sample_views_default_views() {
    $view = new view;
    $view->name = 'sample';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'sample_table';
    $view->human_name = 'Sample';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = false;

    $handler = $view->new_display('page', 'Page', 'page');
    $handler->display->display_options['path'] = 'sample';
    $handler->display->display_options['menu']['type'] = 'normal';
    $handler->display->display_options['menu']['title'] = 'Sample';
    $handler->display->display_options['menu']['weight'] = '0';

    $views['sample'] = $view;

    return $views;
}

```

But when I opened my generated views. The fields of the corresponding table does not show.

Any way to show the fields? Am I missing something to register the fields?

# Answer
> 1 votes
In order for Views to work with custom tables, you need to tell Views about your data structure with hook\_views\_data. The writeup and comments on that page will help you define the guts of the implementation. You basically have to tell views about the table, any relationships (and how), and describe each field in your table and what handler/filter etc it can have.

Aside from that, Data can help wire this automatically, but note that this will require re-defining your table/schema using the Data API.

---
Tags: views
---


title: How to access the request in REST API

text:
# Question
Title: How to access the request in REST API
I'm trying to follow the example of a custom rest api in https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources.

I don't understand how I can access the request for get or post. In the example there is only a default response, but I would of course like to make it depending on the request headers and body.

# Answer
> 3 votes
The only classes that extend `ResourceBase` implemented by Drupal core don't check/use what passed in the request. So I could not use Drupal core code as example.

If you really need to access any request value, and the argument passed to the `get()` or `post()` methods is not enough/adequate for your purpose, you can inject the request object in the `create()` static method.

```
  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, Request $request) {
    parent:: __construct($configuration, $plugin_id, $plugin_definition,  $serializer_formats, $logger);
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('request_stack')->getCurrentRequest()
    );
  }

```

In the class methods you then use `$this->request` to access the request object.

# Answer
> 2 votes
You can always get the current request through `Drupal::request()`:

```
$request = \Drupal::request();

```

---
Tags: 8
---


# Question
Title: Create relationship betweeen content type and custom entity on specific field
I want to create a two-way relationship between a field in a custom entity (*package\_date*) and the field in a content type (*package*).

I have been able to add a relationship from a view for *package\_date*, but it only allows me to add the linked field to the view, not any other *package\_date* field. When the view is saved, I get this error.

> No entity type for field field\_package\_id on view package\_dates in Drupal\views\Plugin\views\HandlerBase-\>getEntityType() (line 697 of core\modules\views\src\Plugin\views\HandlerBase.php)

The *package\_date* entity definition is the following.

```
namespace Drupal\my_module\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityChangedTrait;

/**
 * Defines the PackageDate entity.
 *
 * @ingroup package_date
 *
 * @ContentEntityType(
 *   id = "package_date",
 *   label = @Translation("Package Date"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *   },
 *   base_table = "package_date",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 *   admin_permission = "administer package_date entity",
 *   fieldable = true,
 * )
 */

class PackageDate extends ContentEntityBase {

    use EntityChangedTrait;

  /**
   * {@inheritdoc}
   *
   * Define the field properties here.
   *
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

        // Standard field, used as unique if primary index.
        $fields['id'] = BaseFieldDefinition::create('integer')
            ->setLabel(t('ID'))
            ->setDescription(t('The ID of the Term entity.'))
            ->setReadOnly(TRUE);

        // Standard field, unique outside of the scope of the current project.
        $fields['uuid'] = BaseFieldDefinition::create('uuid')
            ->setLabel(t('UUID'))
            ->setDescription(t('The UUID of the Contact entity.'))
            ->setReadOnly(TRUE);

    $fields['package_id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Package ID'))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'integer',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('view', TRUE);

        $fields['start_datetime'] = BaseFieldDefinition::create('datetime')
        ->setLabel('Package Start Time')
        ->setDisplayOptions('view', array(
            'label' => 'above',
                'type' => 'datetime',
                'weight' => 1,
        ))
        ->setSetting('datetime_type', 'datetime')
        ->setSetting('timezone_override', '');

        $fields['end_datetime'] = BaseFieldDefinition::create('datetime')
        ->setLabel('Package End Time')
        ->setDisplayOptions('view', array(
            'label' => 'above',
                'type' => 'datetime',
                'weight' => 2,
        ))
        ->setSetting('datetime_type', 'datetime')
        ->setSetting('timezone_override', '');

    $fields['price'] = BaseFieldDefinition::create('decimal')
      ->setLabel(t('Package Price'))
      ->setSettings(array(
          'precision' => 10,
          'scale' => 4,
          'decimal_separator' => '.',
      ))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'decimal',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('view', TRUE);

    $fields['capacity'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Capacity'))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'integer',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('view', TRUE);

    $fields['availability'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Availability'))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'integer',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));

    return $fields;
  }
}

```

The `hook_view_data()` implementation uses the following code.

```
function my_module_views_data() {
  $data['package_date']['table']['group'] = t('Package Dates');

  $data['package_date']['table']['join'] = array(
    // Index this array by the table name to which this table refers.
    // 'left_field' is the primary key in the referenced table.
    // 'field' is the foreign key in this table.
    'node__field_package_id' => array(
      'left_field' => 'field_package_id_value',
      'field' => 'package_id',
    ),
  );

  $data['package_date']['package_id'] = array(
    'title' => t('Package ID'),
    'relationship' => array(
      'base' => 'node__field_package_id', // The name of the table to join with.
      'base field' => 'field_package_id_value', // The name of the field on the joined table.
      // 'field' => 'package_id' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Relationship between Package and Package Dates'),
      'title' => t('Package to Package Dates Relationship'),
      'id' => 'standard',
    ),
  );

  return $data;
}

```

The exported view is the following one.

```
langcode: en
status: true
dependencies:
  config:
    - system.menu.admin
  module:
    - datetime
    - pve
    - user
id: _package_dates
label: 'Package Dates'
module: views
description: 'Display current cache of  Package Dates'
tag: ''
base_table: _package_date
base_field: id
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access site reports'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: full
        options:
          items_per_page: 50
          offset: 0
          id: 0
          total_pages: null
          tags:
            previous: ‹‹
            next: ››
            first: '« First'
            last: 'Last »'
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          quantity: 9
      style:
        type: table
      row:
        type: fields
      fields:
        _package_id:
          table: _package_date
          field: _package_id
          id: _package_id
          entity_type: null
          entity_field: _package_id
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Package ID'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: number_integer
          settings: {  }
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
        start_datetime:
          id: start_datetime
          table: _package_date
          field: start_datetime
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Package Start Time'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: datetime_default
          settings:
            timezone_override: ''
            format_type: medium
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: _package_date
          entity_field: start_datetime
          plugin_id: field
        end_datetime:
          id: end_datetime
          table: _package_date
          field: end_datetime
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Package End Time'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: datetime_default
          settings:
            timezone_override: ''
            format_type: medium
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: _package_date
          entity_field: end_datetime
          plugin_id: field
        availability:
          id: availability
          table: _package_date
          field: availability
          relationship: none
          group_type: group
          admin_label: ''
          label: Availability
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: number_integer
          settings:
            thousand_separator: ''
            prefix_suffix: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: _package_date
          entity_field: availability
          plugin_id: field
        capacity:
          id: capacity
          table: _package_date
          field: capacity
          relationship: none
          group_type: group
          admin_label: ''
          label: Capacity
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: number_integer
          settings:
            thousand_separator: ''
            prefix_suffix: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: _package_date
          entity_field: capacity
          plugin_id: field
        created:
          id: created
          table: _package_date
          field: created
          relationship: none
          group_type: group
          admin_label: ''
          label: Created
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: timestamp
          settings:
            date_format: medium
            custom_date_format: ''
            timezone: ''
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: _package_date
          entity_field: created
          plugin_id: field
        changed:
          id: changed
          table: _package_date
          field: changed
          relationship: none
          group_type: group
          admin_label: ''
          label: Changed
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: timestamp
          settings:
            date_format: medium
            custom_date_format: ''
            timezone: ''
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: _package_date
          entity_field: changed
          plugin_id: field
      filters: {  }
      sorts: {  }
      title: 'Package Dates'
      header: {  }
      footer: {  }
      empty:
        area_text_custom:
          id: area_text_custom
          table: views
          field: area_text_custom
          relationship: none
          group_type: group
          admin_label: ''
          empty: true
          tokenize: false
          content: '<p>There is currently no data to display.</p>'
          plugin_id: text_custom
      relationships:
        _package_id:
          id: _package_id
          table: _package_date
          field: _package_id
          relationship: none
          group_type: group
          admin_label: 'Relationship between Package and Package Dates'
          required: false
          entity_type: _package_date
          entity_field: _package_id
          plugin_id: standard
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: 0
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - user.permissions
      tags: {  }
  _package_dates_report:
    display_plugin: page
    id: _package_dates_report
    display_title: 'Package Dates'
    position: 1
    display_options:
      display_extenders: {  }
      path: admin/-package-dates
      menu:
        type: normal
        title: 'Package Dates'
        description: ''
        expanded: false
        parent: system.admin_reports
        weight: 0
        context: '0'
        menu_name: admin
      display_description: ''
    cache_metadata:
      max-age: 0
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - user.permissions
      tags: {  }

```

It looks like the *relationships* property is the wrong way around, but I'm not sure.

I'd also like to be able to create a view for the *package* content type, and link this to the *package\_date* entity. When trying to do so, I don't have a relationship I can add.

I expect I'm missing one or more things to get this working, but I'm not sure what. At the very least, I think I need the inverse of the defined relationship, but I'm sure that's not the only issue.

# Answer
You have actually provided both relationships correctly;

* `$data['package_date']['table']['join']` provides an automatic reference from the external entity to this one; when the other entity is loaded, this one is always available.
* `$data['package_date']['package_id']['relationship']` provides a relationship that needs to be added manually via the views UI.

(If you want them to behave similar, you would have to use `hook_views_data_alter()`) to add one of the above definitions (automatic or manual) to the node entity.)

What I think your problem here (mostly based on Drupal 7 logic), is that you are referring the wrong table. When looking at the complete list of invocations of hook\_views\_data() and for instance look at `book_views_data()`, you will see that all those implementations look like this:

```
$data['book']['table']['join'] = [
  'node_field_data' => [
    'left_field' => 'nid',
    'field' => 'nid',
  ],
];

```

All those joins use the `node_field_data` table, not the field specific table `node__field_package_id` you are using:

```
$data['package_date']['table']['join'] = array(
  // Index this array by the table name to which this table refers.
  // 'left_field' is the primary key in the referenced table.
  // 'field' is the foreign key in this table.
  'node__field_package_id' => array(
    'left_field' => 'field_package_id_value',
    'field' => 'package_id',
  ),
);

```

By providing the value for `left_field`, you are already telling Views to which field you want to use, you you should not access that field directly. I suppose it should work once you change `node__field_package_id` to `node_field_data`.
> 2 votes

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


# Question
Title: Can I use another entity in the route to provide an entity to an entity form?
I am working on a custom content entity that I want to 'link' to a user by adding it as a tab to the user profile. Each user can have one such entity.

My route is defined as follows:

```
entity.my_entity.edit_form:
  path: '/user/{user}/my_entity'
  defaults:
    _entity_form: my_entity.edit
    _title: 'Edit entity'
  requirements:
    _entity_access: my_entity.update
  options:
    user: \d+

```

And the tab (module.links.task.yml):

```
entity.my_entity.edit_form:
  route_name: entity.my_entity.edit_form
  base_route: entity.user.canonical
  title: Entity

```

Though this works and the tabs show up, they result in a fatal error (`cannot return getValue() on null` from the getters) presumably because the form does not have an assigned entity.

If I change the route path to `/user/{user}/my_entity/{my_entity}`, the form works, but I cannot create a tab as the last value is unknown to the routing system.

Can I use the provided user entity instead from the route instead and during the building of the entity form retrieve (and set) the entity I need?

# Answer
> 0 votes
You can use a controller with the user as only route parameter. There you can put the code to retrieve the entity that matches the user and build the entity form:

```
public function myEntityForm(UserInterface $user) {

  // get $my_entity that matches $user

  $form = $this->entityFormBuilder()->getForm($my_entity);

  return $form;
}

```

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


# Question
Title: Displaying relative dates in a Views Exposed Filter
I have a view displaying a collection of events with a date field the user can set the range of. For a default value, I have +0 days to +90 days, so the user can see all events during the next 90 days. The image below shows all my setting information for the date filter.

Currently, the user sees relative dates when they load the page, as the next image shows:

But I would like this to show dates to the user, instead of these relative values when they load the page. In the picture above, if the date they were viewing the page was 1/11/17, I would like the user to see 1/11/17 to 4/11/17 instead of +0 days to +90 days. What would be the simplest way to make this conversion in Drupal 8?

# Answer
> 1 votes
I eventually did something like Ashish's answer but used the hook\_form\_FORM\_ID\_alter hook instead of a view hook.

```
function hook_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (array_key_exists('field_event_start_date_time_value', $form)) {
    $form['field_event_start_date_time_value']['min']['#default_value'] = date('m/d/Y');
    $end_date = new DateTime('+90 days');
    $form['field_event_start_date_time_value']['max']['#default_value'] = date_format($end_date, 'm/d/Y');
   }
 }

```

# Answer
> 0 votes
**Edited -** You can apply datepicker to the field, as Jquery Ui date picker is available in Drupal8. For reference see to this

Or,

you can programmatically alter the view query in `hook_views_query_alter()`

```
function module_name_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
 // Query alter to provide dynamic date ranges.
 if ($view->id() == 'VIEW ID' && $view->current_display == 'page_1')
 {
    foreach ($query->where[0]['conditions'] as $key) {
      if (array_key_exists(':node__field_start_date_time.field_start_date_time_value[]', $key['value'])) {
        // do anything you want...
        ...
        ...
      }
    }
 }

```

---
Tags: 8, views, datetime
---


title: Error applying patch with Git

text:
# Question
Title: Error applying patch with Git
I have read different SE posts and Drupal.org posts about applying patches using git but I am getting an error message whenever I try any of the following methods. the error is:

> error: modules/callbacks.inc: No such file or directory

I tried:

```
curl https://www.drupal.org/files/issues/op_update_should_be_create-2807275-2.patch | git apply -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   668  100   668    0     0   2278      0 --:--:-- --:--:-- --:--:--  2279
error: modules/callbacks.inc: No such file or directory

```

Also, I downloaded the patch into Drupal root and tried:

```
git apply -v op_update_should_be_create-2807275-2.patch

```

The backstory: I was getting the following errors on my website, which I found this discussion explaining that it was because of Entity API, and I was trying to apply the patch in #2.

> Notice: Undefined property: stdClass::$custom in block\_block\_list\_alter() (line 794 of /Applications/AMPPS/www/example/docroot/modules/block/block.module). Notice: Undefined property: stdClass::$visibility in block\_block\_list\_alter() (line 807 of /Applications/AMPPS/www/example/docroot/modules/block/block.module). Notice: Undefined property: stdClass::$pages in block\_block\_list\_alter() (line 817 of /Applications/AMPPS/www/example/docroot/modules/block/block.module).

This is my first time trying to apply a patch.

# Answer
Place **op\_update\_should\_be\_create-2807275-2.patch** into the module folder, in this case being the `sites/all/modules/entity` folder.

Then in your terminal `cd` (change directory) into the module folder.

`cd /var/www/drupal/sites/all/modules/entity`

then

`git apply -v op_update_should_be_create-2807275-2.patch`

In the discussion, Fago has commited this patch (2 months ago), but into the 7.x-.1.x only.

So I assume you're trying to patch the stable version, 7.x-1.8.

If you use/download the latest dev (7.x-1.x-dev) version, it will already have the patch.

**Note:** The rule of thumb, is to use the Stable version rather than the Dev version.
> 1 votes

---
Tags: 7, version-control
---


# Question
Title: Exclude viewing of a field in a view for a content type without excluding content
I have 3 types of content (article, product, service) and a view that displays my content on a page.

In my view I added :

* a title field
* a description field
* a content type field

How do I display all the contents in my view by excluding the display of the "content type" field only on the content type "article" (I do not want to exclude the "article" from my view, only the field) ?

I want "product" and "service" to display the "content type" field.

I do not want "article" to display the "content type"

# Answer
> 0 votes
You can achieve that using Views Conditional.

I have added some random image from the web, just for reference purposes.

**If this field...** `Content type`

**Is...** `Not equal to`

**This value** `Article`

**Then output this...** `[type]`

**Otherwise, output this...** (leave empty/blank)

---
Tags: 7, views, entities
---


# Question
Title: Add to Custom Entity Content on Node add/update
I am new to Drupal. Now, learning drupal 8.

I have added a module from command `drupal generate:module` named 'my\_module\`

I have added an entity for `my_module`:

```
drupal generate:entity:content
//bundle "NO"

```

**What I want**

I would like to add/insert in to this entity on every **Node** add/update.

I have got this code into my `my_module.module`

```
function my_module_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'my_module_node_form_submit';
      }
    }
}

function my_module_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
   $node = $form_state->getFormObject()->getEntity();

   $url = $node->field_website->uri; //my node field
   $name = $node->field_com->value; //my node field

   //HOW TO ADD $url, $name IN TO above custom ENTITY
}

```

My entity table:

**1: my\_module**

```
id
uuid
langcode

```

**2: my\_module\_field\_data**

```
id PrimaryIndex
langcode PrimaryIndex
name
url
status
created
changed
default_langcode Index

```

Please help.

# Answer
> 2 votes
**You can do like this**

*Suppose your entity name is **my\_entity**.*

```
<?php
use Drupal\my_module\Entity\my_entity;

function my_module_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
            $form['actions'][$action]['#submit'][] = 'my_module_node_form_submit';
        }
    }
}

function my_module_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $node = $form_state->getFormObject()->getEntity();

    $url = $node->field_website->uri;
    $name = $node->field_com->value;

    // Now to check
    //Generate my_entity entity.
    $entity = my_entity::create(
               [
                 'label' => 'token',
                 'id' => $node->id(),
                 'status' => true,
                 'name'=> $url,
                  "url" => $name,
                  "created" => time()
               ]
         );
    $entity->save();
}

```

**To update enity:**

```
$entity = my_entity::load('content entity id');
$entity->set("name", 'name value');
$entity->set("url", 'url value');
$entity->save();

```

---
Tags: 8, entities
---


title: Rendering multiple comment form issue

text:
# Question
Title: Rendering multiple comment form issue
I have a view page on which I have rendered the comment form for each node in the field using the code below:

```
  $comment = new stdClass;
  $comment->nid = $n->nid;
  $form = drupal_get_form('comment_form', $comment);
  print render($form);

```

All my forms are printing fine, but the issue is that when I enter a message on message field and click submit, it redirect me to node page with comment form at browser top and my message is lost. If I type and click save here, my message saves without an issue.

I altered the form, added a custom\_submit\_handler as follows:

```
$form['#submit'][] = 'mymodule_custom_submit';

```

and defined it as:

```
function sparx_custom_submit($form, &$form_state) {
 if(isset($form_state['custom_redirect_path'])) {
   $form_state['redirect']  = $form_state['custom_redirect_path'];
 }
}

```

Now the problem I am facing is that each time I try the comment is getting added to the top-most node, not to any other node.

Any suggestions please

# Answer
Using the following code to print comment helped me to solve this issue:

```
module_load_include('inc', 'comment', 'comment.pages');
$comment_form = drupal_get_form('comment_node_<content_type>_form', (object) array('nid' => $nid));
print drupal_render($comment_form);

```
> 0 votes

---
Tags: views, comments
---


# Question
Title: How to display data in blocks of a given size?
Is Drupal 8, which is shown in the accordion (module views\_accordion) the terms of the taxonomy. By default, the module displays the list. I want to display in the blocks of a given size (as the picture)

In the module folder found twig template views-accordion-view.html.twig with the following content:

```
{% if title %}
  <h3 class="js-views-accodion-group-header">{{ title }}</h3>
{% endif %}

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {# A div wrapping the row content is required for the accordion to work #}
  <div{{ row.attributes.addClass(row_classes) }}>
      {{ row.content }}
  </div>
{% endfor %}

```

How to change it for my task? Or is there another way?

# Answer
> 0 votes
copy the file into your custom theme folder and change it in the manner you want , then clear the cache and drupal will use the new file instead

---
Tags: theming, 8
---


# Question
Title: How do I show a field value of a referenced field separately?
I can not write english correctly and very well,I am sorry about this issue.please help me for solving my problem.

How do I show a field value of a referenced field separately with the Views or the Rules module?

I want to show only the referenced field value to visitors.for example :

I have a field (field\_describtion) with label about you , So I want to reference to this field\_describtion and when see the content field\_describtion only show to visitors. I add referenced field\_describtion from a content type and after search on that field and select a field\_describtion value when click on referenced field value linked to referenced node.BUT I want to after click on referenced field (referenced field\_describtion) link to a page that show only field\_describtion (with label about you) to visitors.

I any way to work with this idea ?

My drupal version is 7 and I used entityreference module.

# Answer
I Think found the solution.

I Create a views and add a relation to entityrefence field , So in field of the view I can add another field of referenced content.

for example if we added reference field to users,in a view can add relation to that reference field (go to relations part of views settings) and add another user fields like email or user picture in our views (from fields part of the views settings).picture and email of referenced user show to ours.

Sorry for bad english typing.I hope solve problem of somebody.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Programmatically upload a file to a custom file field
I am trying to update a node and programmatically upload a file.

```
$nid = 45343;
$node = node_load($nid);

$image_url = 'http://test.com/misc/druplicon.png';
$file = system_retrieve_file($image_url, file_default_scheme().'://products_images/'.basename($image_url), TRUE);

// We save the file to the root of the files directory.
// $file = file_copy($file, 'public://');

$node->field_custom_file[LANGUAGE_NONE][0] = (array)$file;
node_save($node);

```

Somehow, it's not working at all. Do I need to add more functions to it?

# Answer
> 1 votes
The following code works for me.

```
$image_url = 'http://test.com/misc/druplicon.png';
$file_info = system_retrieve_file($image_url, 'public://documents/', TRUE);

if ($file_info->fid) {
  $node->field_custom_file['und'][0]['fid'] = $file_info->fid;
}

$node_ready = node_submit($node);
node_save($node_ready);

```

---
Tags: files
---


# Question
Title: How to avoid Exif data rotating images automatically after upload?
an image has been taken upside down, then rotated with any software, then uploaded to my Drupal website and it shows how it was originally taken because it read the Exif metadata.

Is there a way to avoid this?

or, if that's not possible,

how can I add a rotation Image Style drop down that the editor can select when creating the node?

Based on the picture preview, after uploading the picture, the editor would select an Image Style that would set the orientation of the picture right. if the picture is upside down, the editor could selec

# Answer
Please read this article \- no module will be able to correctly interpret EXIF orientation, because there are too many "correct", widely used but contradicting interpretations. Even biggest brands have problems with this. **Even if your site will not rotate image, browser still can.**

To go around this problem, you can use Formatter Field module:

> For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

It's officially still in beta, but that's the best solution I know if you have no control over user's uploads. If you are the only one who uploades, just strip EXIF data (at least orientation part) and make sure you save your files without any, when preparing them for upload.
> 2 votes

# Answer
A better solution is now available. Simply download and enable module Image EXIF Autorotate and all uploads will be automatically rotated respecting the EXIF orientation.
> 0 votes

---
Tags: media
---


# Question
Title: how to check files/images which are more than 400 KB
Related to QA part of our Drupal site performance, we need to make sure that size of images on the site are not more than 400kb.

I know there will validation and configs we can use while uploading images to site. but for already existing, is there any way to find out images size which are more than specified limit?

A non-code solution would be preferred.

# Answer
You can try direct SQL query

```
select fid, filename from file_managed where filemime like 'image/%' and filesize > 400000;

```
> 1 votes

---
Tags: media
---


title: Last articles in front page

text:
# Question
Title: Last articles in front page
I'm using Drupal 8 and I created a global layout with a custom theme I coded myself, and I added a custom content type for the home page. I have almost exactly what I want except for the following points.

1. I should have a block somewhere in the home page containing the last 3 articles posted on the website, and of course, a link to each of these articles. How am I supposed to do that? All answers I found were talking about Drupal 7.
2. I'm supposed to do the same as the last articles but for photos albums. I guess I have to use a module, do I?

# Answer
1. You can use thw Views module, which is a Drupal 8 core module.
On admin/structure/views you can create a new view, even a block view. You can select which content type you want to display, the fields that should appear, and add all your limitations. After you save the view, on /admin/structure/block you can place the block on your preferred region.
2. If you have a content type for the photo albums, you can do exactly the same.
> 1 votes

---
Tags: theming
---


# Question
Title: Unauthorized : CSRF validation failed issue for Logged in user
I need to hide button for Logged in user. For that I have written the following code in dashboard.js file.

Code working fine for anonymous user. But not working for Logged in user.

```
$(document).on("pageshow","#user_login",function(){
      try {
            $.ajax({
              url: "example.com/?q=drupalgap/system/connect.json",
              type: 'post',
              dataType: 'json',
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('page_dashboard - failed to system connect');
                console.log(JSON.stringify(XMLHttpRequest));
                console.log(JSON.stringify(textStatus));
                console.log(JSON.stringify(errorThrown));
              },
              success: function (data) {
                var drupal_user = data.user;
                //console.log(data);
                if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
                alert(drupal_user.uid);
                }
                else { // user is logged in, hide the login button, show the logout button
                  alert(drupal_user.uid);
                }
              }
            });

      } //try end
      catch (error) { alert("page_dashboard - " + error); }
    });

```

For logged in user getting popup like : .

# Answer
Added `X-CSRF-Token` in beforeSend like below everything works fine now.

```
$(document).on("pageshow","#user_login",function(){
      try {

        $.ajax({
              url:"example.com/?q=services/session/token",
              type:"get",
              dataType:"text",
              error:function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
              },
              success: function (token) {

                        $.ajax({
                          url: "http://192.168.0.6/site_name/?q=drupalgap/system/connect.json",
                          type: 'post',
                          dataType: 'json',
                          beforeSend: function (request) {
                                request.setRequestHeader("X-CSRF-Token", token);
                            },
                          error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert('page_dashboard - failed to system connect');
                            console.log(JSON.stringify(XMLHttpRequest));
                            console.log(JSON.stringify(textStatus));
                            console.log(JSON.stringify(errorThrown));
                          },
                          success: function (data) {
                            var drupal_user = data.user;
                            //console.log(data);
                            if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
                            //alert(drupal_user.uid);
                             // $('#button_login').show();
                             // $('#edit-user-login-form-name').hide();
                            }
                            else { // user is logged in, hide the login button, show the logout button
                              //$('#edit-user-login-form-pass').hide();
                              alert(drupal_user.uid);
                             //$('#button_logout').show();
                            }
                          }
                        });

                    }
        });

      } //try end
      catch (error) { alert("page_dashboard - " + error); }
    });

```
> 0 votes

---
Tags: 7, javascript, csrf
---


# Question
Title: field_view_value returns null for boolean field
I have a custom field `field_sold` which contains a single boolean value. I'm trying to use the following function to retrieve the content of the field, but it always seems to return null:

```
function <theme>_render_field($node, $field_name, $delta = 0, $display = array()) {
   $field = field_get_items('node', $node, $field_name);
   $field = field_view_value('node', $node, $field_name, $field[$delta], $display);
   return render($field);
}

```

When trying to dumping the `$field` variable between the calls to `field_get_items()` and `field_view_value()` I recieve the following output:

```
// after field_get_items()
Array ( [0] =>
   Array ( [value] => 1 ) )
// after field_view_value()
Array ( [#markup] => [#access] => 1 )

```

When I'm using the above function for other fields it works as expected, for instance when rendering a image field like this:

```
print <theme>_render_field($node, 'field_image', 0,
                     array('type' => 'image',
                           'settings' => array(
                           'image_style' => 'object_200x300',
                           'image_link' => 'content')
                           ));

```

# Answer
> 1 votes
Set

```
$display['type'] = 'list_key';

```

in your theme function to get not null key of field. Or create own formatter, for ex.

```
function mymodule_field_formatter_info() {
  return array(
      'my_formatter' => array(
          'label' => t('My formatter'),
          'field types' => array('list_boolean'),
      ),
  );
}

function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
    case 'my_formatter':
      foreach($items as $delta => $item) {
        $value = $item['value'] == 1 ? '<span class="">ON TEXT</span>' : '<span class="">OFF TEXT</span>';
        $element[$delta] = array(
            '#markup' => $value,
        );
      }
      break;
  }

  return $element;
}

```

and after that set

```
$display['type'] = 'my_formatter';

```

in Your theme function

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


title: Login in a different way

text:
# Question
Title: Login in a different way
For some reason i don't have access to `user/login` block and don't have a `region content` .
is there any way to login without them like drush,url ?

# Answer
Reset the theme to bring back the content region with drush

```
drush vset theme_default 'bartik'

```

Then login at `example.com/user/login`
> 2 votes

# Answer
You can login using the following drush command:

```
drush user-login

```
> 0 votes

---
Tags: users
---


# Question
Title: Drupal 8 Webform - Pass submitted value from one webforms to another
I have two webforms on my Drupal 8 website. When a user submits the first webform, I have the confirmation redirect set to a second webform. I would like to populate one of the fields in the second webform with one of the submitted values from the first form. I have it set up as two separate webforms as some users will by-pass the first form and go directly to the second webform where they can manually enter the content into the field I need populated. Any idea how I can achieve this?

Thanks

F

# Answer
Ok I figured it out - for anyone else who comes across this question.

In the first Webform, I set the Confirmation URL to:

**/form/my-form2**?**value**=\[webform\_submission:values:**element\_key**\]

*I've bolded the elements in the URL that you will need to adjust for your webforms.*

This will result in redirecting the user from my first Webform to the second Webform (which is at the URL www.mydomain.com/form/my-form2) when they click the submit button. It will append ?value=\[the value from the webform field\] to the end of the URL.

Then in the second form in the field where I want this value to go, I have set the Default value for this field as

\[current-page:query:**value**\]

The word 'value' in the above can be anything, but it must match the id used in the URL from the first form.

And hey presto - it works!

F
> 6 votes

---
Tags: webforms
---


# Question
Title: Display webform submitted data in profile page
I have created a webform with several fields. I have implemented webform registration module too. Now if the user registers, Soon after clicking register button he will need to see his profile page with the submitted values.I can use tokens for this but it's not a good idea because user should be able to edit his profile page too. -I have tried displaying webform submissions on view.which doesn't work here. -But specifically a user should see his profile page with submitted data after submitting the webform -Please help me on this.

# Answer
> 1 votes
If you're willing to use Webform Rules in combination with Rules, you can use the webform data (as submitted via the webform) in a custom rule (to copy those webform date to the relevant profile fields). Because you have access to all ***labels*** and all ***values*** of any field of a webform, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

With that, you should be able to create a custom rule with:

* Rules Event: After a webform has been submitted.
* Rules Conditions: Check the form's id (possibly with other conditions to further refine them, eg that the user is not logged in).
* Rules Action(s): Set a data value (for the appropriate profile fields, and using the values submitted via the webform).

For more details about this approach, and a prototype rule to understand the idea, refer to the answer to "How to create a node from a Webform using rules?":

* the *1st attempt* relates to using "Entity has field" (which doesn't work for Webform)
* the *2nd attempt* explains what to do in case of Webform.

PS: I'm assuming your question is about D7 ...

---
Tags: webforms
---


title: Optimizing CSS Delivery in Theme

text:
# Question
Title: Optimizing CSS Delivery in Theme
I ran my site through Google PageSpeed Insights and got the following message:

**Optimize CSS delivery of the following:**

**First** it lists two CSS files I don't recognize in /sites/default/files

**Second**, it lists my font awesome css which I'm LINKING to from my `.libraries.yml` file, like so:

```
font-awesome:
  remote: https://fortawesome.github.io/Font-Awesome/
  version: 4.5.0
  license:
    name: MIT
    url: https://fortawesome.github.io/Font-Awesome/license/
    gpl-compatible: true
  css:
    theme:
      https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-
awesome.min.css: { type: external, minified: true }
    bootstrap/assets/javascripts/bootstrap/transition.js: {}

```

**So my question then is two-fold:**

Short of using another module such as Addvagg

1) How can I speed up delivery of the font awesome css?

2) What are those other CSS files and how can I speed up delivery of them?

# Answer
1. download the font & css files, don't use a cdn
2. minify and concat your css, additionally you can use sass & gulp to do the job for you
> -1 votes

---
Tags: theming, 8
---


# Question
Title: Featurize user roles and permissions can't update
I have added user roles and permissions to feature which I use to featurize general site configurations and theme settings.

In the past I believe this worked just fine, however, with my latest push the remote created additional roles instead of changing the names as I had done on dev. I deleted the old roles and kept the ones with the proper names. MySQL drupal.role shows that the roles now have new IDs also which I believe could be the cause of the problem. I shouldn't have deleted the roles that matched dev but since I already did, where do I go from here? Should I manually change the ID's in MySQL?

I'm working on a new site that isn't launched yet but will be importing users from another site.

Here you can see the original role IDs and what is on dev:

Here you can see the role ID's on prod now:

# Answer
> 0 votes
Since production hasn't yet been released and is still under development, I took a risk of mysqldump the drupal.role table and then importing them on prod, which fixed the issue.

LongBoardNode's suggestion of editing the RID on dev would have probably been a better idea,

---
Tags: 7, users, features, version-control
---


# Question
Title: Access denied to custom REST API endpoint for anonymous user
I have developed a custom D8 REST API endpoint, and using the REST UI module, I have enabled it and set access to be allowed for the anonymous user using the permission created by REST UI. However, when I try to access the endpoint - either via Postman or with the D7 Feeds importer - I am unable to access the endpoint because I get a 403 - Forbidden return status code.

The settings for the endpoint in the REST UI settings provides the choices of basic or cookie authentication methods. Is the option of allowing anonymous access to a GET endpoint via the provided permission really doable, or is it required to actually send some type of authentication header?

Thanks.

# Answer
So it looks like there is a core issue that doesn't permit leaving out some type of REST authentication. The easiest solution appears to be the Feeds HTTPFetcher AA (Advanced Authentication) module, as it allows you to enter your authentication credentials in the custom parser settings. The downside is that I have to create a user (and possibly a role) in D8 for this, but at least it's workable.
> 0 votes

---
Tags: 8
---


# Question
Title: How to modify the class names of socialmedia module
I am using social media module. When I inspect the page in chrome, I see some div classes. My css is conflicting with module css classes. I was thinking to modify module's div classes. I was looking for the tpl file inside social media folder but I could not find it.

Which file in social media module has the div classes so I can modify the div classes?

# Answer
> 2 votes
As you can see here https://jsfiddle.net/81kbx4f4/, if you do an inspect element, you will see them here too.

Those are added by facebook and it's not something that you can control.

---
Tags: theming
---


# Question
Title: How to get an import of a very large Drupal database working?
I'm using Vagrant and OracleVM to run Drupal 7. I've got the site up and running and I'm trying to get my database imported. So far I've run `drush cc` and cleared the drush cache, and then I did

```
drush sql-cli < mydb.sql

```

The drush command is taking a super long time and I'm not sure if it's even doing anything. The database file is just under a gigabyte.

What can I do to get this working, or is there a better method?

# Answer
I'm not sure how much overhead drush puts on top of large SQL imports, I've only used it for smaller imports and queries. You can try the mysql client as an alternative that would remove the drush overhead.

If you can install pipe viewer on your VM you can view the progress of the command consuming the import.

```
pv mydb.sql | drush sql-cli

```

Or without the drush overhead

```
pv mydb.sql | mysql -u <DB_USER> -p<DB_PASS> <YOUR_DB>

```
> 6 votes

# Answer
Smaller databases will import more quickly, so `drush cc all` and `drush watchdog delete all` will speed things up considerably, if dropping these is an option.

Also, to expand on Shawn Conn's answer, you can use pipe viewer without the Drush overhead, and still use Drush to look up the database credentials for you if you use `drush sql-connect` instead of `drush sql-cli`. Just use `$()` to execute the mysql line that `drush sql-connect` prints out:

```
pv mydb.sql | $(drush sql-connect)

```
> 6 votes

# Answer
The Backup and Migrate module has a feature to exclude selected tables, such as:

* all cache\_\* tables
* ctools\_views\_cache
* ctools\_object\_cache
* flood
* history
* queue
* semaphore
* watchdog
* search\_index (usually saves a lot of database size!)

The issue about Default tables/data to exclude, also includes an interesting list of tables to not be migrated (pick what fits for you), i.e. (quote from it):

> When creating a backup profile, the module by default sets the following tables to have their data excluded according to issue #209647: Exclude advice:
>
> * cache
> * cache\_filter
> * cache\_calendar\_ical
> * cache\_menu
> * cache\_page
> * cache\_views
> * sessions
> * search\_dataset
> * search\_index
> * search\_keywords\_log
> * search\_total
> * watchdog
> * accesslog
> * devel\_queries
> * devel\_times
> 5 votes

# Answer
It's better to trim the big database on dump by using `drush sql-dump` to dump the SQL file. This gives you the advantage to specify the additional options to skip the specific tables when dumping (such as cache or migrate tables).

This can be either specified in the command line (see: `drush help sql-dump`) or configure it in your *drushrc* file as shown in `example.drushrc.php` like:

```
$options['structure-tables']['common'] = array('cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');
$options['skip-tables']['common'] = array('migration_*');

```

or per host basis like if you're using `sql-sync` or `sql-dump` between remotes:

```
$aliases['global'] = array(
  // These options will only be set if the alias is used with the specified command.
  'command-specific' => array(
    'sql-sync' => array(
      'structure-tables-key' => 'common',
      'skip-tables-key' => 'common',
      'structure-tables' => array(
        // You can add more tables which contain data to be ignored by the database dump
        'common' => array('cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog'),
      ),
      'skip-tables' => array(
        'common' =>array('migration_*'),
      ),
    ),
    'sql-dump' => array(
      'ordered-dump' => FALSE,
      'structure-tables-key' => 'common',
      'skip-tables-key' => 'common',
    ),
  ), // end: command-specific
);

```

Then you can load this settings into your host via:

```
$aliases['stage'] = array(
  // ...
) + $aliases['global'];

```

Then you can try something like:

```
drush @source sql-dump | drush @self sql-cli

```

To monitor the progress, you can add pipe viewer (`pv`) in between (like `... | pv | ...`).

See also:
> 5 votes

# Answer
You seem to have resolved the issue, but here comes one for me:

> drush sql-dump \> mydb.sql
> 0 votes

---
Tags: 7, drush, database, virtual-machine
---


title: Restful web services Documentation

text:
# Question
Title: Restful web services Documentation
I am looking for complete and updated documentation for Restful web services.

For example, for the user login, we have to post the following data.

```
POST: http://example.com/user/login?_format=json
Content-type: application/json
Data: { "name": "admin", "pass": "myPassword" }
Response: 200 OK

```

This will properly log in via cookie authentication, and return a result similar to this.

```
    {
      "current_user": {
        "uid":"1",
        "roles":["authenticated"],
        "name":"admin"
      },
      "csrf_token":"abc123",
      "logout_token":"def456"
    }

```

How do I log out the user I just logged in with?

I found RESTful Web Services module overview, but I still don't understand how to log out.

Using the following request gets back a 403 Forbidden error.

```
POST: http://example.com/user/logout?_format=json
Content-type: application/json
Data: { "name": "admin" }

```

What am I missing?

# Answer
As per documentation you can do like this.

**Logout**

```
GET http://example.com/user/logout
Content-type: text/html
200 - OK

```

Note: Do not pass **"?\_format=json"** it is not accepting.
> 0 votes

---
Tags: 8
---