# Question
Title: Custom REST POST resource to accept JSON
I am trying to build simple search autocomplete POST endpoint, that accepts JSON and outputs JSON, but I am having problems getting Drupal 8 to just accept plain JSON.

Currently I am getting a 404 error for that endpoint, even though it is enabled in REST UI and I have permission. If I add `serialization_class` with value `Drupal\node\Entity\Node` to the class comment, I get 415 error, because it expects a node. Okay, great. How do I actually make it accept JSON? Do I really need to make an Entity type just for my autocomplete search?

Here is the code I have in mymodule/src/Plugin/rest/resource/SearchAutocompleteResource.php.

```
namespace Drupal\MyModule\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\node\Entity\Node;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Provides a resource for search autocomplete.
 *
 * @RestResource(
 *   id = "mymodule:searchautocomplete",
 *   label = @Translation("MyModule: Search Autocomplete"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/search-autocomplete",
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/search-autocomplete"
 *   }
 * )
 */
class SearchAutocompleteResource extends ResourceBase {

  public function post($search = null) {

    return new ResourceResponse(array(
      'example' => 'return value'
    ));

  }

}

```

# Answer
Up until Make serialization\_class optional (#2419825) issue has been fixed for `8.2.x` branch you couldn't get away without creating a custom serialization class which merely passes the provided data to satisfy the requirement for mandatory serialization.

If you need to make it work on Drupal \<= 8.1, try the following:

1. Create a custom normalizer.
2. Expose it to the system as a service.
3. Use it as `serialization_class` for your Rest resource.

`modules/mymodule/src/normalizer/JsonDenormalizer.php:`

```
<?php

namespace Drupal\mymodule\normalizer;

use Drupal\serialization\Normalizer\NormalizerBase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

/**
 * Class JsonDenormalizer
 *
 * @todo Remove this class once https://www.drupal.org/node/2419825 is fixed.
 */
class JsonDenormalizer extends NormalizerBase implements DenormalizerInterface {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var array
   */
  protected $supportedInterfaceOrClass = array(__CLASS__);

  /**
   * {@inheritdoc}
   */
  public function normalize($object, $format = null, array $context = array()) {
    return parent::normalize($object, $format, $context);
  }

  /**
   * {@inheritdoc}
   */
  public function denormalize($data, $class, $format = NULL, array $context  = array()) {
    return $data;
  }
}

```

`modules/mymodule/mymodule.services.yml:`

```
services:
  # can be removed once https://www.drupal.org/node/2419825 is fixed.
  serializer.normalizer.mymodule.json:
    class: Drupal\mymodule\normalizer\JsonDenormalizer
    tags:
      - { name: normalizer }

```

`mymodule/src/Plugin/rest/resource/SearchAutocompleteResource.php:`

```
/**
 * Provides a resource for search autocomplete.
 *
 * @RestResource(
 *   id = "mymodule:searchautocomplete",
 *   label = @Translation("MyModule: Search Autocomplete"),
 *   serialization_class = "Drupal\mymodule\normalizer\JsonDenormalizer",
 *   uri_paths = {
 *     "canonical" = "/api/v1/search-autocomplete",
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/search-autocomplete"
 *   }
 * )
 */

```
> 7 votes

# Answer
The answer supplied by @maijs is correct for Drupal 8.1.x and lower, but for 8.2.x it's *so* much easier, because you don't even have to think about the normalizer. Here's an example of `my_module/src/Plugin/rest/resource/MyRestResource.php`

```
<?php

namespace Drupal\my_module\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "my_rest_resource",
 *   label = @Translation("My rest resource"),
 *   serialization_class = "",
 *   uri_paths = {
 *     "canonical" = "/my_rest_resource"
 *   }
 * )
 */
class MyRestResource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@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('my_module'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to GET requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get() {
    $response = 'hello world';
    return new ResourceResponse($response);
  }

  public function post(array $data = []) {
    $response = array(
      "hello_world" => $data,
    );
    return new ResourceResponse($response);
  }

  public function patch($arg) {
    return new ResourceResponse('hello patch');
  }

}

```

The key here is `post(array $data = [])` near the bottom of the file. In 8.1.x that was impossible, but in 8.2.x that's all it takes to convert post data to an array. Here's how it looks when you request that URL with postman:
> 4 votes

# Answer
This is what I did to receive a JSON object from a post.

```
use Symfony\Component\HttpFoundation\Request;

class AjaxController extends ControllerBase {
    public function save(Request $request) {
        $object = json_decode($request->getContent());

```
> 1 votes

---
Tags: entities, 8
---


# Question
Title: Why are some of my teasers only show up inside the view preview and not on the page?
I've got a view that is displaying a couple different content types in teaser form. Everything looks fine in the view preview but when I look at the actual page, only one content type is displaying the teaser. I've tried comparing them and don't see any differences that would make any difference. Does anyone have an idea what the problem could be?

This is a screenshot of my view.

>

# Answer
> 0 votes
For each content type, go to "manage display" and then "Teaser". Make sure all the fields in there are set the same way as the content type that is working.

---
Tags: 7, views
---


# Question
Title: Export and import configuration settings and content
I have created two sites. They have the same modules and themes available, however I want them to be complete clones of each other without doing a manual database export and import.

I attempted using Drupal 8's configuration synchronization but I receive the following message

```
The staged configuration cannot be imported,
because it originates from a different site than this site.
You can only synchronize configuration
between cloned instances of this site.

```

I've attempted using the Features module. But I don't see an option for exporting and importing to separate sites.

I've also looked at a similar question here Sync content between two Drupal sites However that applies to Drupal 7.

Is there a way to import and export nodes, site settings, and configurations such as menu items and what modules are turned on or off from one site to another?

UPDATE: I've discovered that I might be able to use configuration synchronization if I get the UUIDs to match, but I'm having trouble running drush on my multisite. Is there a way to manually change the UUID in the database?

# Answer
> 0 votes
See this question and answers on why what you want to do is not possible at the moment.

How to add the configuration changes from a website to another website?

---
Tags: 8, features, configuration
---


# Question
Title: The block X was assigned to the invalid region footer and has been disabled
I am seeing the following:

The block X was assigned to the invalid region footer and has been disabled. The block Y was assigned to the invalid region footer and has been disabled. The block Z was assigned to the invalid region footer and has been disabled. The block W was assigned to the invalid region search and has been disabled.

Here is my code

```
array(
  'module' => 'W',
  'delta' => 'form',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'search',
  'pages' => '',
  'cache' => -1,
  'visibility' => BLOCK_VISIBILITY_NOTLISTED,
),
array(
  'module' => 'X',
  'delta' => '1',
  'theme' => $admin_theme,
  'status' => true,
  'weight' => 0,
  'region' => 'footer',
  'pages' => '',
  'cache'  => -1,
  'visibility' => BLOCK_VISIBILITY_NOTLISTED,
),
array(
  'module' => 'Y',
  'delta' => '2',
  'theme' => $admin_theme,
  'status' => true,
  'weight' => 0,
  'region' => 'footer',
  'pages' => '',
  'cache'  => -1,
  'visibility' => BLOCK_VISIBILITY_NOTLISTED,
),
array(
  'module' => 'Z',
  'delta' => '3',
  'theme' => $admin_theme,
  'status' => true,
  'weight' => 0,
  'region' => 'footer',
  'pages' => '',
  'cache'  => -1,
  'visibility' => BLOCK_VISIBILITY_NOTLISTED,
),

```

);

Any suggestion greatly appreciate it. I have other blocks that have properly worked using this method with the custom theme. But the above in $admin\_theme = 'seven'; are not working.

# Answer
It doesn't work because regions are *theme specific*. The only way you can have cross theme block export/import is to have the same regions (machine name) defined in your admin theme.
> 0 votes

---
Tags: theming, blocks
---


title: Login page theme

text:
# Question
Title: Login page theme
I have created my own theme in drupal 7 using only `page.tpl.php` as I am happy to use the same template for every node/page.

When visiting *mysite.com/?q=user/login* every sidebar-navbar from my theme appears there as expected and I would like to remove them from the login form though I really want to avoid creating the login template *page--user--login.tpl.php*. I was thinking of using the default body class somehow

`<body class="html not-front not-logged-in no-sidebars page-user page-user-login">
<body class="maintenance-page in-maintenance no-sidebars">`

`no-sidebars` maybe?

# Answer
> 1 votes
The sidebar is appearing as there will be some content(blocks) displayed on it.

So, in blocks section, you need to configure those blocks listed there, and in **Show block on specific pages** section, select "***All pages except those listed***" and add *user/login* in the textarea below.

# Answer
> 0 votes
I have temporary solved the issue by using a little bit of css to hide the sidebar and, to eliminate the html, the following:

`<?php if ($logged_in): ?><div class="mysidebar"></div><?php endif; ?>`

I am not sure if there is a way drupal will eliminate the side bar when there is not block on them.

Furthermore, I leave this here so I hope it is helpful to somebody

> General utility variables:
>
> * $base\_path: The base URL path of the Drupal installation. At the very least, this will always default to /.
> * $directory: The directory the template is located in, e.g. modules/system or themes/bartik.
> * $is\_front: TRUE if the current page is the front page.
> * $logged\_in: TRUE if the user is registered and signed in.
> * $is\_admin: TRUE if the user has permission to access administration pages.

---
Tags: 7, theming, users
---


title: Move from Wp to Drupal without downtime

text:
# Question
Title: Move from Wp to Drupal without downtime
If I have wordpress right now with a bit of content (on a linux VPS with apache) and I want to switch over to drupal with the least possible downtime what do you recommend? Is it possible to install drupal separately and then put the content in it and then make it active over the wordpress somehow? Sorry if this was a silly thought as I don't have experience with any of this.

# Answer
Based on what you've mentioned, you will want to install drupal 7 separately and try Wordpress Migrate.

https://www.drupal.org/project/wordpress\_migrate

It only needs the export of Wordpress which can be done in the Wordpress admin.

You will want to try this out first on your own machine, Acquia Dev Desktop will work for you. Read through some of the docs and walkthroughs on the migration. I've done it a few times, it's very quick and typically works fine.

https://www.acquia.com/products-services/dev-desktop

Once you are setup and established, you can migrate to Drupal 8.2.x-8.3.x without much trouble.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: How do you show/hide delete(remove) product button in the Cart?
I have an issue with the delete/remove product button from the Shopping Cart. Some of my products show and some don't (see screenshot below). I checked the rules and can't find this anywhere.

What I am trying to achieve is to have the `Remove` on another collection I created. It only works for Postpaid Collection which is the BLU Studio X product. However, the `Remove` link doesn't appear on the top product (above the red arrow where I want the `Remove` to show on that product as well).

There is a rule set somewhere and I can't find it. I even created a new product variation and content, and it doesn't show the link in the shopping cart. It only shows it for the Phone product that was created by the previous user.

# Answer
Shopping cart in Drupal commerce is a view. To remove the "remove" link, all you need to do is edit it and remove the "remove" field.

The view can be found at `/admin/structure/views/view/commerce_cart_form/edit`
and remove the field `(Line items referenced by commerce_line_items) Commerce Line Item: Delete button (Remove)`
> 1 votes

# Answer
I finally figured this bit out, I fixed this by checking the custom modules the previous developer added, and found that I had to add the line item type of the product, in the php code.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to Exclude a Specific Node from a Block View
I know you can exclude the current node from a list view.

What I'm trying to do is exclude a specific node from a block view.

I have a list of the Top 5 Viewed pages I created into a block view, but I'm trying to hide one of them that keeps showing as it's the home page. I'd like to exclude that from the view.

Is it possible? I couldn't find anything in Contextual Filters.

I'm using Drupal 7 btw

Regards Tony

# Answer
You can filter `Content:Nid` in the view and select `is not equal to` operator.
> 0 votes

# Answer
Just add a filter on node id which excludes the node in question
> 0 votes

---
Tags: blocks, views
---


# Question
Title: Circular Search view not returning results if city exists in UK AND elsewhere
We have a locational search (using circular search filter in the View) available for our member groups across the UK: https://makingmusic.org.uk/resources/find-a-group-list

Entering cities/towns by name such as 'London' returns results correctly, but where there is a town/city with the same name abroad (e.g. 'Durham' or 'Cambridge' which both also exist in the US) no results are returned unless the country is included: 'Durham, UK' or 'Cambridge, UK'.

Since the search should only cover the UK (and so there shouldn't be a conflict caused by a place name existing outside the UK) is there a setting where I can limit the search criteria so that it only looks for places in the UK (and so doesn't get stuck where the name appears somewhere other than the UK as well)?

# Answer
The Geofield proximity Views filter doesn't have any default location settings. The filter passes the given string value on through to the geocoder without any additional settings:

```
  $geocoded_data_raw = geocoder($geocoder_engine, $location);

```

As such, your only option is to form alter the submitted data as answered in this question:

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#submit'], 'MYMODULE_form_views_exposed_form_submit');
}

/**
 * Modify submission value with " UK" if given origin has been supplied.
 */
function MYMODULE_form_views_exposed_form_submit($form, &$form_state) {
  if (isset($form_state['values']['field_geofield_distance']['origin']) &&
      strlen($form_state['values']['field_geofield_distance']['origin']) > 0) {
    $form_state['values']['field_geofield_distance']['origin'] .= ' UK';
  }
}

```
> 0 votes

---
Tags: location
---


# Question
Title: Composer module doesn't contain a .info file
So I am quite new to Drupal and I was hoping someone experienced could tell me what I am doing wrong.
Essentially, I have Drupal 7.5 linked to my website, but I am having problems installing the Composer module using the control panel.
Whenever I attempt to add the module by either URL or a local download, Drupal claims that it doesn't include a .info file. Which, from what I can tell after unpacking it and inspecting its contents, is true.
So, I was wondering if the lack of a .info file is a problem on my end (likely) or just a case of the Composer devs forgetting to include it (unlikely).
Hopefully someone will be able to help out.

# Answer
> 1 votes
The project you linked to is a Drush extension, not a module, and only compatible with Drupal 8.

So it makes sense that you can't install it as a module into a Drupal 7 site ;)

# Answer
> 0 votes
As the project page says, that is not a module, but a Drush extension.

> Since this is Drush extension that works across all versions of Drush, it doesn't need a different release for each different Drupal version. Hence this just being an 8.x project.

In fact, it does miss the .info (or .info.yml) file necessary to Drupal to recognize it as module, but it also misses a .module file.

There are module that are also Drush extensions, but this is not the case. It is hosted as module on drupal.org simply for the fact drupal.org doesn't have *Drush extension* as project type, so you need to necessarly select *module* if you want to host a Drush extension on drupal.org.

---
Tags: 7, composer, .info
---


# Question
Title: How to view and inspect a Commerce Billy invoice pdf template as HTML, before it's passed to the PDF generator?
I'm trying to customise a Commerce Billy pdf invoice template. I've seen Custom PDF template in Commerce Billy which tells me what I need to know about which files to edit to do this.

What I can't see how to do is, see the template as rendered by HTML before it's converted into a PDF. I need to do this to see what CSS classes are being applied where, and because testing changes to the HTML and CSS layout is much easier in HTML and CSS using inspect element tools than constantly re-generating PDFs.

How can I see a Commerce Billy PDF template as it is rendered as HTML before it is passed to the PDF generator? Right now, I'm just guessing about how the rendered PDF will look when I make changes, then repeatedly re-rendering PDFs, which is an inefficient way of working. I'd like to be able to try different CSS changes using developer tools in a browser, then apply those changes to a file and check they apply cleanly, *then* generate test PDFs.

# Answer
> 2 votes
If you check the page callback of PDF URL (i.e. "invoice-pdf/%commerce\_order"), the HTML output of Invoice PDF is generated using `commerce_billy_pdf_html($order)` function. Same function is used by Print Invoice URL (i.e. "invoice-pdf/%commerce\_order/print") to generate Printable output of Invoice. Since print page render HTML output you can inspect the output easily.

So for example, if your order number is 1 and your Invoice PDF URL is "invoice-pdf/1", then you can see the HTML Structure of PDF Output by going to "invoice-pdf/1/print" page.

Hope this helps.

---
Tags: 7, commerce
---


# Question
Title: Inspecting HTTP headers when requesting a route generated from Views
I have a content view with a REST Export display, and I want to inspect the HTTP request headers and look for a custom header, denying access to the view if the header's value is not on a whitelist. I was planning to use a hook called early in the view, like `hook_views_pre_view()`, and maybe some of the tools provided by Symfony's `HttpFoundation` to grab the request headers, but I'm not sure how to put all together. Any suggestions?

# Answer
> 4 votes
You can add a `_custom_access` requirement to any route via a custom RouteSubscriber extending off of `RouteSubscriberBase`. This requirement will add a method which can check the request headers to take action accordingly.

Define your event subscriber class in your **mymodule.services.yml**:

```
services:
  test.route_subscriber:
    class: Drupal\mymodule\Routing\MyRouteSubscriber
    tags:
      - { name: event_subscriber }

```

Within your **src/Routing/MyRouteSubscriber.php** class file extend `RouteSubscriberBase` with an `alterRoutes(RouteCollection $collection)` method:

```
namespace Drupal\mymodule\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Add _custom_access to the my_view_machine_name REST export display
    if ($route = $collection->get('view.my_view_machine_name.rest_export_1')) {
      $route->setRequirement('_custom_access', '\Drupal\mymodule\Controller\MyCustomAccessController::access');
    }
  }
}

```

Within your **src/Controller/MyCustomAccessController.php** class file, perform the `AccessResult`logic:

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Custom controller adds additional checks to REST data export view.
 */
class MyCustomAccessController {

  /**
   * Checks access for a specific request.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(AccountInterface $account) {
    $allowed = FALSE;
    $request = \Drupal::request();
    // @TODO: Add logic based off of $request->headers.
    return AccessResult::allowedIf($allowed);
  }
}

```

---
Tags: views, 8
---


# Question
Title: Updating a taxonomy term, with extra fields - taxonomy_term_update does not exist
In Drupal 7, I am trying to update and delete some taxonomy terms in the proper way. So, instead of attacking the database directly, I am using `taxonomy_term_delete` for deleting by **tid**. However I cannot find `taxonomy_term_update` and about `taxonomy_term_save`, it seems not to have access to the extra fields that I added (a few fields, text and integer).

How can I make the following *pseudocode* to work? ( this does not pretend to work, it is just some *pseudocode* in a dialect of Drupal to make the question more understandable )

```
 $term = taxonomy_term_load ( $tid )   // or equivalent function
 $term->extra_field_1 = 23; // extra_field_1 would be numerical
 taxonomy_term_save($term) // o taxonomy_term_update or equivalent

```

Result: the extra\_field\_1 value of that term ( with tid = $tid ) is set to 23.

# Answer
> 1 votes
try

```
    $terms = taxonomy_term_load($tid);
    // echo "<pre>";
    // print_r($terms);
    // die();
    //dsm($terms);
    $terms->extra_field_1[LANGUAGE_NONE][0][$column_name] = 23;
    taxonomy_term_save($terms);

```

Use print\_r or dsm(devel module if installed) and check the "$column\_name".

After print the $terms you able to get "$column\_name" replacement. Update that and save.

---
Tags: 7, entities, taxonomy-terms, updating
---


# Question
Title: How to display node in view and allow users add comment?
Is it possible to display a node in a view and allow users to add comments to the node?

I have not been able to find a way to do this.

# Answer
Yes, you can show node in view and also allow users to add comment. See example below:

1. Create a view normally.
2. Under Format section, change **Show** settings to **Content**
3. Select the view mode as **Full Content** and enable **Display Comments**. (Check screenshot below)
4. Click on Apply
> 1 votes

# Answer
You would need a contrib module to get this functionality, it's called AJAX Comments

After installing it you will have new views fields available (screenshot), that will:

a) Allow you to add comments
b) Allow you to display the existing comments

An important point is that following for this issue, AJAX Comments integration with Views adds auto-refresh support in order to display the newly added comments.
> 0 votes

# Answer
If you wants to add comment form to a view

Refer add comment form in views @No Sssweat describe it very nicely.

You need to add a global php field and render the comment form.

And display one node you can add filter conditions.
> 0 votes

---
Tags: views
---


title: default email not showing up in webform

text:
# Question
Title: default email not showing up in webform
I had used files of a website to create new website. I had changed the database and user details in settings.php. Now everything is working fine except email settings in webform. It is showing old informations as default.

I need the default email to be "noreply@pharmahelpdesk.net". In Configuration \> System \> Site Information , I had used the same email id. But it is not getting updated. Due to this I am not receiving emails. Please see the images and suggest.

.

# Answer
> 0 votes
I think here is a option to change default email `admin/config/content/webform`.

---
Tags: webforms, configuration
---


# Question
Title: Install Drupal in a subfolder of an existing website
I have a question about drupal installation in a subfolder: We have an existing website running on Magento. Now for some special functionalities we need to build some drupal pages, which all should be in a subfolder. Example. Main URL is (Magento): www.mysite.com Drupal installation: www.mysite.com/specialpages all other pages are still Magento as today, e.g. www.mysite.com/page1, www.mysite.com/folder1/page12 etc.

Is it possible to install drupal in this subfolder?

thanks for any help / information

# Answer
> 1 votes
Drupal and Magento both use .htaccess rules for functionality. One slight quirk with Apache is that .htaccess is processed from a directory up through all of the parents. This means that if your Drupal install is inside your Magento install, Magento's .htaccess *may* interfere with Drupal (a Magento directive may be applied after a Drupal one). This is going to totally depend on your setup. At very least, you will likely need to set `RewriteBase` in the Drupal .htaccess for things to work properly. I have seen similar situations work perfecty fine, but others fail in bizarre ways.

# Answer
> 0 votes
Yes why not, you can install drupal in a sub-folder and provide drupal pages link in your magento website. That should not be a problem.

# Answer
> 0 votes
Just want to give a short feedback: We have installed drupal in the subfolder and all is working well. There was just one problem: relative links in css files of the theme did not work relative to the drupal installation but relative to the main installation.So we had do adjust these paths (setting baseurl etc. did not work). relative links in modules worked well.

---
Tags: installation
---


# Question
Title: How do I programmatically alter and rewrite the current path?
I have a multilingual site with 2 languages (English and French) and 4 ISO codes (us, gb, fr, and be). I want Drupal to understand that /us and /gb are aliases for /en. (They share the same content.)

Is there a way to programmatically achieve this?

# Answer
I was able to achieve what I wanted using the following service.

### services.yml

```
mymodule.path_processor:
  class: Drupal\mymodule\PathProcessor\PathProcessor
  arguments: ['@language_manager', '@config.factory', '@path.alias_manager']
  tags:
    - { name: path_processor_inbound, priority: 200 }

```

### PathProcessor.php

```
/**
 * Processes the inbound path using path alias lookups.
 */
class PathProcessorCustom implements InboundPathProcessorInterface, OutboundPathProcessorInterface {

  protected $language_manager;
  protected $configFactory;
  protected $aliasManager;

  public function __construct(LanguageManagerInterface $language_manager, ConfigFactoryInterface $config_factory, AliasManagerInterface $alias_manager) {
    $this->languageManager = $language_manager;
    $this->configFactory = $config_factory;
    $this->aliasManager = $alias_manager;
  }

  public function processInbound($path, Request $request) {
    if (!strpos($path, '/admin/')) {
      $path = $this->removeISOCode($path);
    }

    return $path;
  }

  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if (!strpos($path, '/admin/')) {
      $path = $this->insertISOCode($path);
    }

    return $path;
  }

  protected function removeISOCode($path) {
    $langcode = $this->languageManager
      ->getDefaultLanguage()
      ->getId();
    $isocodes = $this->getISOCodeMapping();
    $path_items = explode('/', $path);
    if (isset($path_items[1]) && strlen($path_items[1]) == 2 && in_array($path_items[1], $isocodes[$langcode])) {
      $config_negotiation_url = $this->configFactory->get('language.negotiation')->get('url');
      if (!in_array($path_items[1], $config_negotiation_url['prefixes'])) {
        array_splice($path_items, 1, 1);
        if (count($path_items) == 1) {
          $config_system_site = $this->configFactory->get('system.site')->get('page');
          $path = $config_system_site['front'];
        }
        else {
          $path = implode('/', $path_items);
          $path = $this->aliasManager->getPathByAlias($path, 'en');
        }
      }
    }

    return $path;
  }

  protected function insertISOCode($path) {
    $path_items = explode('/', $path);
    if (isset($path_items[1]) && strlen($path_items[1]) == 2 && $path_items[1] == 'gb') {
      $config_negotiation_url = $this->configFactory->get('language.negotiation')->get('url');
      if (!in_array($path_items[1], $config_negotiation_url['prefixes'])) {
        $path_items[1] = $language;
      }
    }

    return implode('/', $path_items);
  }

  protected function getISOCodeMapping() {
    return [
      'en' => ['gb', 'us'],
      'fr' => ['fr', 'be']
    ];
  }

}

```

What I do is decompose the URL, remove what I know I don't need, and map the URL to an actual content URL.
> 3 votes

---
Tags: 8, uri
---


# Question
Title: Help with contextual filter and entity reference fields
I have a content type with an entity reference field that allows users to assign multiple other nodes to be referenced from the current node.

I am trying to create a view that will list the related nodes for the current page.

What Relationship/s and contextual filters must be set to achieve such a thing?

I have read a number of other posts asking similar questions, though most seem to be in reference to Drupal 7 and their suggestions either do not work, or appear to not exist in Drupal 8.

I can get a list which shows all the other nodes that reference the current node by setting a contextual filter to: `Content:field_related_pages` and setting the default value to `Content ID from URL` this, however, is the exact opposite of what I want...

I have tried creating a relationship based on the Entity Reference field, however there are two options I can see:

* `Content referenced from field_related_pages`
* `Content using field_related_pages`

I have also tried using a contextual filter of: `Content: ID` with the default value set to `Content ID from URL`

I feel like I have attempted every conceivable combination of the above and none seems to work. Can someone please put me out of my misery and incompetence and please how to get a contextual filter to show a list of nodes related to the current via a entity reference field?

# Answer
Apparently I had the following selected under the "more" tab in the contextual filter:

`Exclude If selected, the numbers entered for the filter will be excluded rather than limiting the view.`

Which lead to all kinds of odd behaviour...

If it is of use to anyone else, the correct answer appears to be:

* `Content using field_related_pages` with the relationship required.
* The contextual filter set to Content: ID with with the \`\`\`default value set to Content ID from URL\`\` and
* Relationship dropdown set to the `field_related_pages`
> 0 votes

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


title: How to set permission in custom module?

text:
# Question
Title: How to set permission in custom module?
I have a custom module and i want the "form-example" only open for admin user and form-submissions open for anyone.

> **form-example.module**

```
<?php
function form_example_permission() {
  return array(
    'submit form_example' => array(
      'title' => t('Submit form_example'),
      'description' => t('Submit the form_example form'),
    ),
    'access form_example submissions' => array(
      'title' => t('Access form_example submissions'),
      'description' => t('Access the form_example submissions'),
    ),
  );
}
function form_example_menu() {
  $items = array();

  $items['form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit form_example'),
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'),

      );

 $items['form-submissions'] = array(
    'title' => t('List'),
    'page callback' => 'form_example_submissions',
    'access callback' => TRUE,
    'access arguments' => array('access form_example submissions'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function form_example_form($form, &$form_state) {

$form['empcode'] = array(
  '#weight' => '0',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Code'),
);
$form['empname'] = array(
  '#weight' => '1',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Name'),
);
$form['file'] = array(
  '#weight' => '2',
  '#type' => 'file',
  '#size' => '30',
  '#title' => t('Employee Photo'),
);
 $form['submit'] = array(
     '#weight' => '3',
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

return $form;

}

function form_example_form_validate($form, &$form_state) {
  /*if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }*/
 // print('<pre>'.print_r($form_state['values'],1).'</pre>');
  //die();
 $file = file_save_upload('file', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

function form_example_form_submit($form, &$form_state) {
   $file=$form_state['values']['file'];
  unset($form_state['values']['file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));

 $fe_id = db_insert('form_example')
        ->fields(array(

          'empcode' => $form_state['values']['empcode'],
          'empname' => $form_state['values']['empname'],
          'empphoto' => $file->filename,
        ))
        ->execute();
        drupal_set_message(t('Successfully added'));

}
function form_example_theme($existing, $type, $theme, $path) {
  return array(
    'form_example_function' => array(
      'variables' => array('rows' => NULL),
    ),
    'form_example_template' => array(
      'variables' => array('rows' => NULL),
      'template' => 'form_example_template',
    ),

  );
}

/* view the form submissions*/
function form_example_submissions()
{
  $results =  db_query("Select * from {form_example}");
   $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->fe_id,
        $result->empcode,
        $result->empname,
        $result->empphoto,
      );

  }
  return theme('form_example_function',array('rows' => $rows));
}
/*function theme_form_example_function($variables)
{
  print_r($variables);
//$output ="<h2>".print_r$variables."</pre></h2>";
/*  foreach ($variables as $result)
  {

    $output = "<h2><pre>".print_r($result)."</pre></h2>";
  }
return $output;
 $output = '';

    foreach($variables['rows'] as $row) {
        foreach($row as $values) {

          print_r($values);
         $output .= "Empcode: " . $values . "</br> ";
         // $output .= "EmpName: " . $values[1] . " </br>";
        //$output .= "Emphot: " . $values[2] . "\n";
        }
    }
    return $output;

}*/
function theme_form_example_function($variables)
{
    $output = '';

    foreach($variables['rows'] as $row) {
      //  echo $path;
      // $output .= "Empcode: " . (isset($row[1]) ? $row[1] : "--") . " ";
      //  $output .= "EmpName: " . (isset($row[2]) ? $row[2] : "--") . " ";
      //  $output .= "Emphot: " . (isset($row[3]) ? $row[3] : "--") . "<br>";

$img_url = 'public://'.(isset($row[3]) ? $row[3] : "--");  // the orig image uri
$style = 'medium';  // or any other custom image style you've created via /admin/config/media/image-styles

     $output .= '<div class="views-row"><div class="do_featured">
  <div style="position: relative;" class="do_image">
            <div class="field field-name-field-thumb-image field-type-image field-label-hidden"><div class="field-items"><div class="field-item "><img  src="'.image_style_url($style, $img_url).'" ></div></div></div></div>
  <div class="do_title">
    <span>    <div class="field"><div class="field-items">Employee Name:</div><div class="field-items">'.(isset($row[2]) ? $row[2] : "--") .'</div></div>
 <div class="field"><div class="field-items">Employee Code:</div><div class="field-items">'.(isset($row[1]) ? $row[1] : "--") .'</div></div>

      </span>
   </div></div></div>';

    }

    return $output;
}

?>

```

# Answer
> 0 votes
Give your admin role permissions for 'submit form\_example', and then give both authenticated and anonymous roles permission for access 'form\_example submissions'.

---
Tags: users
---


# Question
Title: How to disable front page view programmatically?
I have another view that uses the same path as the front page view which is "/node" and I will like to disable the front page view programmatically.

How can I do that from a **hook\_install**?

# Answer
> 13 votes
Views are entities, so:

1. Load the View:

```
$view_id = 'content'; // Replace with the ID of the view you wish to disable.
$view = \Drupal::entityTypeManager()->getStorage('view')->load($view_id);

```
2. Update the status:

```
$view->setStatus(FALSE);

```
3. And save it:

```
$view->save();

```

Or all in one go:

```
\Drupal::entityTypeManager()->getStorage('view')
  ->load($view_id)
  ->setStatus(FALSE)
  ->save();

```

# Answer
> 3 votes
Even simpler - with the only real drawbacks being that you need a use statement for `View` and it assumes that is the class for view objects, which would be very unusual not to be the case:

```
View::load('content')->disable()->save();

```

---
Tags: views, 8
---


# Question
Title: how to make a custom filter in custom module?
i am creating a custom module \**

> form\_example.module

\**

```
<?php
function form_example_permission() {
  return array(
    'submit form_example' => array(
      'title' => t('Submit form_example'),
      'description' => t('Submit the form_example form'),
    ),
    'access form_example submissions' => array(
      'title' => t('Access form_example submissions'),
      'description' => t('Access the form_example submissions'),
    ),
  );
}
function form_example_menu() {
  $items = array();

  $items['form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Employess Entry Form', //page title
    'description' => "A form to submit the employee's data.",
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit form_example'),
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'),

      );

 $items['form-submissions'] = array(
    'title' => t('List'),
    'page callback' => 'form_example_submissions',
    'access callback' => TRUE,
    'access arguments' => array('access form_example submissions'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function form_example_form($form, &$form_state) {

$form['empcode'] = array(
  '#weight' => '0',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Code'),
);
$form['empname'] = array(
  '#weight' => '1',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Name'),
);
$form['empemail'] = array(
  '#weight' => '2',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Email'),
);
$form['empdesignation'] = array(
  '#weight' => '3',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Designation'),
);
$form['file'] = array(
  '#weight' => '4',
  '#type' => 'file',
  '#size' => '30',
  '#title' => t('Employee Photo'),
);
 $form['submit'] = array(
     '#weight' => '5',
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

return $form;

}

function form_example_form_validate($form, &$form_state) {
  /*if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }*/
 // print('<pre>'.print_r($form_state['values'],1).'</pre>');
  //die();
 $file = file_save_upload('file', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

function form_example_form_submit($form, &$form_state) {
   $file=$form_state['values']['file'];
  unset($form_state['values']['file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
 // drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));

 $fe_id = db_insert('form_example')
        ->fields(array(

          'empcode' => $form_state['values']['empcode'],
          'empname' => $form_state['values']['empname'],
          'empemail' => $form_state['values']['empemail'],
          'empdesignation' => $form_state['values']['empdesignation'],
          'empphoto' => $file->filename,
        ))
        ->execute();
        drupal_set_message(t('Successfully added'));

}
function form_example_theme($existing, $type, $theme, $path) {
  return array(
    'form_example_function' => array(
      'variables' => array('rows' => NULL),
    ),
    'form_example_template' => array(
      'variables' => array('rows' => NULL),
      'template' => 'form_example_template',
    ),

  );
}

/* view the form submissions*/
function form_example_submissions()
{
  $results =  db_query("Select * from {form_example}");
   $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->fe_id,
        $result->empcode,
        $result->empname,
        $result->empphoto,
        $result->empemail,
         $result->empdesignation,
      );

  }
  return theme('form_example_function',array('rows' => $rows));
}
/*function theme_form_example_function($variables)
{
  print_r($variables);
//$output ="<h2>".print_r$variables."</pre></h2>";
/*  foreach ($variables as $result)
  {

    $output = "<h2><pre>".print_r($result)."</pre></h2>";
  }
return $output;
 $output = '';

    foreach($variables['rows'] as $row) {
        foreach($row as $values) {

          print_r($values);
         $output .= "Empcode: " . $values . "</br> ";
         // $output .= "EmpName: " . $values[1] . " </br>";
        //$output .= "Emphot: " . $values[2] . "\n";
        }
    }
    return $output;

}*/
function theme_form_example_function($variables)
{
    $output = '';
print_r($variables);
    foreach($variables['rows'] as $row) {
      //  echo $path;
      // $output .= "Empcode: " . (isset($row[1]) ? $row[1] : "--") . " ";
      //  $output .= "EmpName: " . (isset($row[2]) ? $row[2] : "--") . " ";
      //  $output .= "Emphot: " . (isset($row[3]) ? $row[3] : "--") . "<br>";

$img_url = 'public://'.(isset($row[3]) ? $row[3] : "--");  // the orig image uri
$style = 'medium';  // or any other custom image style you've created via /admin/config/media/image-styles

     $output .= '<div class="views-row"><div class="do_featured">
  <div style="position: relative;" class="do_image">
            <div class="field field-name-field-thumb-image field-type-image field-label-hidden"><div class="field-items"><div class="field-item "><img  src="'.image_style_url($style, $img_url).'" ></div></div></div></div>
  <div class="do_title">
    <span>    <div class="field"><div class="field-items"><b>'.(isset($row[2]) ? $row[2] : "--") .'</b></div></div>
 <div class="field"><div class="field-items">Emp Code:  </div><div class="field-items">'.(isset($row[1]) ? $row[1] : "--") .'</div></div>
 <div class="field"><div class="field-items">'.(isset($row[4]) ? $row[4] : "--") .'</div></div>
 <div class="field"><div class="field-items">'.(isset($row[5]) ? $row[5] : "--") .'</div></div>

      </span>
   </div></div></div>';

    }

    return $output;
}

?>

```

> I want to show only filters on form-submissions like below:

> After filter the data screen will shown like below

> i want to know how can i add these filter on page and search the result on database and shown on page

# Answer
I am adding an example for this. Hope this will helps you.

```
function form_example_list(){
    $search_form =drupal_get_form('form_example_search_form');
    $content = '<div class="block" >'.drupal_render($search_form).'</div>';
    $content .= '<div style="clear:both" ></div>';

    $query = db_select('form_example', 'pd');
    if(isset($_GET['empname']) && $_GET['empname'] != ''){
        $query->condition('pd.empname', $_GET['empname'],'=');
    }
    if(!empty($_GET['empcode'])){
        $query->condition('pd.empcode', $_GET['empcode'],'=');
    }
    if(isset($_GET['empdesignation']) && $_GET['empdesignation'] != ''){
        $query->condition('pd.empdesignation', $_GET['empdesignation'],'=');
    }
    $query->fields('pd');
    //$table_sort = $query->extend('TableSort')->orderByHeader($header);
    //$pager = $table_sort->extend('PagerDefault')->limit(10);

    $result = $query->execute();
 return $content;
}
function form_example_search_form($form, &$form_state){

    $form['#method'] = 'get';
    $form['#token'] = FALSE;
    $form['#form_build_id'] = FALSE;
    $form['#form_id'] = FALSE;
    $form['empname'] = array(
        '#type' => 'textfield',
        '#title' => t('empname'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '<div class="form-inline views-exposed-form"> <div class="views-exposed-widget">',
        '#suffix' => '</div>',
        '#default_value' => isset($_GET['empname'])?$_GET['empname']:'',
    );
    $form['empcode'] = array(
        '#type' => 'textfield',
        '#title' => t('empcode'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '<div class="form-inline views-exposed-form"> <div class="views-exposed-widget">',
        '#suffix' => '</div>',
        '#default_value' => isset($_GET['empcode'])?$_GET['empcode']:'',
    );
    $form['empdesignation'] = array(
        '#type' => 'textfield',
        '#title' => t('empdesignation'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '<div class="form-inline views-exposed-form"> <div class="views-exposed-widget">',
        '#suffix' => '</div>',
        '#default_value' => isset($_GET['empdesignation'])?$_GET['empdesignation']:'',
    );
    //views-exposed-widget

    $form['submit'] = array(
        '#type' => 'submit',
        '#attributes' => array( 'name' => ''),
        '#prefix' => '<div class="views-exposed-widget">',
        '#suffix' => '</div></div>',
        '#value' => 'Apply',
     );

    return $form;
}

```

// Fetch data as per you requirement means you may need like operator. Depend on situations.

After getting the result you can design as per your requirement.
> -1 votes

---
Tags: views
---


# Question
Title: How to get the content moderation entity related to node entity in drupal 8.2.x?
from a content moderation entity, i know how to get the associated node:

```
 if ($entity->getEntityTypeId() == 'content_moderation_state' ) {
     $article_id=$entity->get('content_entity_id')->getString();
     $article = \Drupal\node\Entity\Node::load($article_id);
 }

```

What i need to do is the reverse. Being able from hook\_form\_alter, to get the content moderation entity related to the node:

```
 function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if ($form_id='node_article_edit_form')
  {
    $node=$form_state->getFormObject()->getEntity();
    //$node->get_content_moderation_entity??

}

```

}

# Answer
i did it with entityQuery

```
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
 if ($form_id='node_article_edit_form')
  {
    $article=$form_state->getFormObject()->getEntity();
    //get the associated content moderation entity
    $id = Drupal::entityQuery('content_moderation_state')
       ->condition('content_entity_id', $article->id())
        ->execute();

    $stateEntities = Drupal::entityManager()
        ->getStorage('content_moderation_state')
        ->loadMultiple($id);
    $stateEntity=array_values($stateEntities)[0];
    $moderation_state = $stateEntity->get('moderation_state')->getString();
   }
 }

```
> 1 votes

---
Tags: 8, entities, forms
---


title: How to apply FILE in views field

text:
# Question
Title: How to apply FILE in views field
I like to make a custom view for the module entity browser. For some reasons I do not want to install the module entity browser empamples. But I make the experience as I created the view that there are no file options to select only content options. Can anybody help?

# Answer
When you create a new view, you can choose on which entity the view is based on. In the first picture the view is based on *File*, in the second picture it is based on *Content* (nodes).

You only see the fields of that source you have selected.

Another method to get the fields from *File* would be to configure a relationship using a reference field. But this is then additional, you get fields from both tables by doing this.
> 4 votes

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


# Question
Title: How to send forget pass email programatically?
I implemented Decoupled Drupal in one of my projects, one of the features I need to implement is a `forget password` feature. So I created a custom route to listen to reset password requested.

I know I can create a reset password URL with `user_pass_reset_url()`; I can generate this link and programmatically set the email to that user, but I am looking for a service or Drupal core functionality to achieve this job.

How can I programmatically send a reset password email?

# Answer
With some reverse engineering on core user module the solution is :

```
    $name = \Drupal::request()->get("name");
    $langcode =  \Drupal::languageManager()->getCurrentLanguage()->getId();
    // Try to load by email.
    $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(array('mail' => $name));
    if (empty($users)) {
        // No success, try to load by name.
        $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(array('name' => $name));
    }
    $account = reset($users);
    // Mail one time login URL and instructions using current language.
    $mail = _user_mail_notify('password_reset', $account, $langcode);

```
> 13 votes

---
Tags: users, 8
---


# Question
Title: Cannot find /libraries for installing ckeditor module
I'm trying to install the CKEditor Codesnippet module. I've downloaded the source but I don't know how to install it.

In the module page istructions are:

> Download the plugin from http://ckeditor.com/addon/codesnippet at least version 4.5.11.
>
> Place the plugin in the root libraries folder (/libraries).
>
> Enable CodeSnippet in the Drupal admin.
>
> Configure your WYSIWYG toolbar to include the button.

I cannot find the /libraries folder. Should I create it in the root folder of Drupal installation or somewhere else?

# Answer
> 1 votes
Make sure you have the the Libraries API module installed/enabled. Some details about it (from its project page):

> The common denominator for all Drupal modules/profiles/themes that integrate with external libraries.
>
> This module introduces a common repository for libraries in `sites/all/libraries` resp. `sites/<domain>/libraries` for contributed modules.

# Answer
> 1 votes
You can (need to) create it in the web root.

---
Tags: 8, wysiwyg
---


# Question
Title: How to skip the ReferenceAccess constraint on a file upload by an anonymous user?
I have a contact form for job applications with a file field on it so users can upload their CV. Because of privacy / security, the uploaded CV's must be stored in the private filesystem.

Unfortunately, a problem occurs when an anonymous user tries to add a CV and submit the form. Since the anonymous user does not have access to the uploaded file, the file field's ReferenceAccess constraint (`\Drupal\Core\Entity\Plugin\Validation\Constraint\ReferenceAccessConstraint`) kicks in and throws a validation error: `You do not have access to the referenced entity (file: 1)`. As a consequence, the user is not allowed to submit the form.

Is there a way to tell Drupal to skip the ReferenceAccess constraint when anonymous users reference a file that they just uploaded themselves?

Update: I came to realize that this does not happen when using the core file field, only with the File Entity module.

# Answer
> 4 votes
That constraint is validated by `\Drupal\Core\Entity\Plugin\Validation\Constraint\ReferenceAccessConstraintValidator`. `ReferenceAccessConstraintValidator::validate` uses the following code.

```
  /* @var \Drupal\Core\Entity\FieldableEntityInterface $referenced_entity */
  $referenced_entity = $value->entity;
  if ($referenced_entity) {
    $entity = $value->getEntity();
    $check_permission = TRUE;
    if (!$entity->isNew()) {
      $existing_entity = \Drupal::entityManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
      $referenced_entities = $existing_entity->{$value->getFieldDefinition()->getName()}->referencedEntities();

      // Check permission if we are not already referencing the entity.
      foreach ($referenced_entities as $ref) {
        if (isset($referenced_entities[$ref->id()])) {
          $check_permission = FALSE;
          break;
        }
      }
    }

    // We check that the current user had access to view any newly added
    // referenced entity.
    if ($check_permission && !$referenced_entity->access('view')) {
      $type = $value->getFieldDefinition()->getSetting('target_type');
      $this->context->addViolation($constraint->message, [
        '%type' => $type,
        '%id' => $id,
      ]);
    }
  }

```

(In particular, see the line containing `$referenced_entity->access('view')`.)

We can hook into the file's access control to alter the outcome, with `hook_entity_access()` or `hook_ENTITY_TYPE_access()`.

Another solution could be to create a new field type which inherits everything from `Drupal\file\Plugin\Field\FieldType\FileItem`, except for the `ReferenceAccess` constraint in its plugin definition. You can do this in two ways:

1. Create a new plugin class that extends the original class, and copy and modify its docblock, including the `@FieldType` annotation.
2. Implement `hook_field_info_alter()`, copy the `file` plugin definition to your own, and make the necessary adjustments there.

---
Tags: forms, 8, files
---


title: Load order of JS files

text:
# Question
Title: Load order of JS files
Hey I have added the following libraries:

```
my-google-maps:
  js:
    https://maps.googleapis.com/maps/api/js?key=my_funkey_key&: {type: external, weight: -400, attributes: {defer: true,async: true}}
my_other_lib:
  header: true
  js:
    js/mylib.js: { }
  dependencies:
    - core/drupal
    - core/drupalSettings

```

I have tried multiple ways to attach these files in a specific order(first google and then my custom js:

```
{{ attach_library('my_module/my-google-maps') }}
{{ attach_library('my_module/my_other_lib') }}

```

If it is not in the specific order the map is undefined.How can I specific the load order?

# Answer
The libraries are loaded by weight, not in the order they are defined.

You already had figured that out. You have set a weight of -400 for the external library. This will be the first library loaded, because in drupal the lowest weight for a library is -22. But most times you would want to be above -20, because this is the weight of jquery, on which most libraries depend.

The problem in your case is, that the library mylib.js is specified to be loaded in head. So the external library will never be able to come ahead. It's loaded at top of all other libraries because of the low weight, but still with the bunch of all the other libraries at the end of the document.
> 6 votes

---
Tags: 8, theming
---


# Question
Title: Difficulties install Drush using composer
I have tried to install Drush on OSX 10.9 but it doesn’t seem to have worked. In terminal ‘drush status’ gives

> -bash: drush: command not found

I have followed the instructions on http://whaaat.com/installing-drush-7-using-composer

Composer’s directory seems to be correct as my .bash\_profile contains:

```
export PATH="$Trotter/.composer/vendor/bin:$PATH"

```

Drush exists in the vendor folder of composer

When I tried to install Drush via composer the feedback seemed to suggest it had worked:

```
Pauls-iMac:~ Trotter$ composer self-update
Updating to version 8e9659bd8317ad3f623c4d17940380443cf8772c.
    Downloading: 100%
Use composer self-update --rollback to return to version 1.0.0-alpha9
Pauls-iMac:~ Trotter$ composer global require drush/drush:7.*
Changed current directory to /Users/Trotter/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing pear/console_table (1.2.1)
    Loading from cache

  - Installing symfony/var-dumper (v2.7.1)
    Downloading: 100%

  - Installing symfony/yaml (v2.7.1)
    Downloading: 100%

  - Installing d11wtq/boris (v1.0.8)
    Loading from cache

  - Removing drush/drush (6.5.0)
  - Installing drush/drush (7.0.0)
    Downloading: 100%

pear/console_table suggests installing pear/Console_Color2 (>=0.1.2)
symfony/var-dumper suggests installing ext-symfony_debug ()
d11wtq/boris suggests installing ext-pcntl (*)
Writing lock file
Generating autoload files
Pauls-iMac:~ Trotter$ drush status
-bash: drush: command not found

```

(Note I had previously tried to install Drush 6 but hadn't got this to work either)

I would appreciate any advice on what is going wrong here.

# Answer
> 5 votes
Changing the .bash\_profile to the following worked:

```
export PATH="~/.composer/vendor/bin:$PATH"

```

Now drush status gives good feedback on the Drush version etc. Thanks to Clive for suggesting this.

# Answer
> 2 votes
The linked manual may be outdated. Please follow the steps below.

## Installing `drush`

### via Phar binary

Download latest stable release using the command below:

**OS X/Unix**:

```
sudo wget -O /usr/local/bin/drush http://files.drush.org/drush.phar
sudo chmod +x /usr/local/bin/drush

```

**Linux**:

```
sudo install <(curl http://files.drush.org/drush.phar) /usr/local/bin/drush

```

**Windows and other**

Download manually at https://github.com/drush-ops/drush/releases

### via Composer

If you'd like to install `drush` globally (for all users) and `/usr/local/bin` is already in your `PATH`, try installing using the following syntax:

```
sudo COMPOSER_HOME=/opt/drush COMPOSER_BIN_DIR=/usr/local/bin COMPOSER_VENDOR_DIR=/opt/drush/7 composer require drush/drush:7

```

or:

```
sudo COMPOSER_HOME=/var/lib/composer COMPOSER_BIN_DIR=/usr/local/bin COMPOSER_VENDOR_DIR=/var/lib/composer/vendor composer require drush/drush:7

```

Change `drush/drush:7` into `drush/drush:dev-master` for the latest development version.

### via Homebrew (OS X)

Run:

```
brew install drush

```

---

See: Install/Upgrade a global Drush

# Answer
> 0 votes
I have found the simplest way is to install it with Homebrew

Once brew is installed and working simple type `brew install drush`.

# Answer
> 0 votes
My .bash\_profile contains exactly

```
export PATH="$PATH:$HOME/.composer/vendor/bin"

```

and my drush lies here (Acquia DevDesktop)

```
export PATH="$PATH:/Applications/DevDesktop/drush"

```

# Answer
> 0 votes
This article for installation of Composer with Drush included can be useful:

https://www.pcextreme.nl/community/d/138-drush-installation-for-drupal-shared-hosting

---
Tags: drush
---


title: 'Access denied' to Content Type

text:
# Question
Title: 'Access denied' to Content Type
I've a website that I didn't build that is giving me some trouble. A whole Content Type is returning "access denied" error when authenticated users try to view it (Guests can). The access is only denied when a field is set to 1, but the are no dependencies set. I really can't figure out from who the access is beeing denied.

I didn't find any access content modules.

Has somebody any ideas?

# Answer
> 1 votes
From the limited details provided in your question, it could very well be that one of your enabled rules (created with the Rules module) is what is causing your issue.

To actually confirm, for sure, if it is any of the enabled rules, use these steps:

* Disable of all your enabled rules. If the problem persists, you can be sure it is not because of a custom rule (don't forget to re-enabe the temporary disabled rules). If the problem is gone, continue with the next step to find which rule is causing your problem.
* Re-enable your temporary disabled rules, but only 1 at a time, and check if your problem comes back (each time after you re-enabled one more rule). At some point your problem should come back. As soon as that happens, the most recent re-enabled rule is what is causing your issue. In that case, re-enabe the remaining temporary disabled rules and continue with the next step.
* If you cannot find out what the actual problem might be in the re-enabled rule that causes the problem, move on to Rules **debugging**, as explained in my answer to "How can I display the value of a variable inside a condition?".

After you're sure it's not Rules causing the problem, I'd consider the "Workflow" module (which you also seem to be using) as the next suspect on my list. As a quick test (to see if that's the direction to go for further debugging), temporary disable the Workflow module: if the problem remains, then it is not the Workflow module either (don't forget to re-enable it afterwrds).

---
Tags: users
---


title: Google Store Locator

text:
# Question
Title: Google Store Locator
I have installed this module on a clean Drupal 7 installation. But I can't activate the Google API. I have added the API key in the GEOCODE field. But I still get the error.

Also I got a blanc screen when I add location via the content type Store Location. Maybe because the API key isn't working?

My API key:

Got it from Google API:

After clearing the cache, I still get the error:

And no Google Maps:

Thanks.

# Answer
> 0 votes
Actually you need to different keys one for the browser (client side) and one for the server . You already have configured your server key but you need to get a new key from google developer dashboard for the browser side . then go to google\_store\_locator.module line 441 and change it to :

```
'js' => array('//maps.googleapis.com/maps/api/js?sensor=false&libraries=places&key=' . variable_get('geocoder_apikey_google_client') => array('type' => 'external')),

```

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


# Question
Title: How do I make a view block with picture of the currently logged-in user?
How do I make a view block with picture of the currently logged-in user? I am using Drupal 8.

# Answer
> 2 votes
1. Create a new view `/admin/structure/views`.

2. Add a contextual filter in view: `User: User ID` and configure.

3. Add picture field.
4. Save.
5. Show block where you need.

# Answer
> 1 votes
If you use the 'Picture' field of user, create your view like this.

1. Goto /admin/structure/views/add
2. View settings
    * Show -\> Users
3. Block settings
    * Create a block
4. Save and Edit
5. Add field 'Picture'
6. Click on 'ADVANCED' and add 'Contextual filters'

* Add 'User ID' -\> Provide default value -\> Use ID from logged in user -\> Apply
7. Save and add your bloc to the page.

You can also do it programmatically like : http://www.drupal8.ovh/en/tutoriels/107/create-a-simple-block-programmatically Then use following codes to get the image.

```
$userCurrent = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($userCurrent->id());
$output[] = $user->get('user_picture')->first()->view();
return $output;

```

---
Tags: views
---


title: How do I set the cookie lifetime?

text:
# Question
Title: How do I set the cookie lifetime?
I'm having trouble setting the cookie lifetime in my D8 instance. I'd like to set it to zero so that closing the browser logs-off the user.

I've added `ini_set('session.cookie_lifetime', 0);` to the site/default/settings.php file. There was no previous cookie\_lifetime reference in the file. I added the line. I've also cleared the Drupal cache and cleared my Chrome cache. Sadly, it's not being respected. Sessions still persist after browser close.

I've searched the entire codebase for `ini_set('session.cookie_lifetime', 200000);` but it doesn't appear to exist in my site. I don't see where Drupal is setting the cookie lifetime. I've also tried adding the setting via a php.ini file in the root but that's being over-ruled by Drupal.

I feel like this is a simple thing, so I'd like to avoid plugins. Looking forward to hearing from everyone. Thanks in advance.

# Answer
For the session cookie options D8 uses container parameters instead of settings. Create a `services.yml` file in the same folder as `settings.php`. The default values are in `default.services.yml`. You can copy this file to `services.yml` and modify it:

**/sites/default/services.yml:**

```
parameters:
  session.storage.options:
    # Default ini options for sessions.
    #
    # Some distributions of Linux (most notably Debian) ship their PHP
    # installations with garbage collection (gc) disabled. Since Drupal depends
    # on PHP's garbage collection for clearing sessions, ensure that garbage
    # collection occurs by using the most common settings.
    # @default 1
    gc_probability: 1
    # @default 100
    gc_divisor: 100
    #
    # Set session lifetime (in seconds), i.e. the time from the user's last
    # visit to the active session may be deleted by the session garbage
    # collector. When a session is deleted, authenticated users are logged out,
    # and the contents of the user's $_SESSION variable is discarded.
    # @default 200000
    gc_maxlifetime: 200000
    #
    # Set session cookie lifetime (in seconds), i.e. the time from the session
    # is created to the cookie expires, i.e. when the browser is expected to
    # discard the cookie. The value 0 means "until the browser is closed".
    # @default 2000000
    cookie_lifetime: 2000000

```
> 27 votes

---
Tags: 8, cookies
---


# Question
Title: Show entity reference content with a field other than the title
I want to add a field to a custom content type that allows users to select other content from the site to display as a list on the given node.

I can do this by creating an entity reference field to content type. This works, but I can only seem to have it show the link in reference to the Title field of the corresponding node. I want to set a different field as the link. How do I do this?

If I could show the fields in a view, I could select the field to show more easily, however, I have not found a way to have a view show the contents of a field from the current page.

Originally, I had implemented this via a system of taxonomy terms and a view but my users want the ability to go in and manually set the relationships so I have had to fall back to this. If someone has a better suggestion for this problem I would love to hear it.

# Answer
I've done this before:

You can override the Autocomplete field widget, so instead of title, it will give you back something else! You need to inheritance the existing one and after 2-3 of other inheritance you will be able to reach the autocomplete ajax functionality and rewrite it. It's pretty complex, but not impossible!
> 2 votes

# Answer
I think this is the module you are looking for: https://www.drupal.org/project/inline\_entity\_form
> 0 votes

---
Tags: theming, 8, entities
---


# Question
Title: How to connect database in UnitTestCase subclass?
I know there are mockups, data providers, bla bla bla. I don't care now, I just want to connect to my dev site db and use nodes, terms for unit tests.

How can I do it? In D7 it was very simple in plain PHPUnit, what about D8?

I've tried bootstrap D8, but failed.

# Answer
See https://www.drupal.org/phpunit for better documentation.

There are 4 test base classes:

* UnitTestBase, pure unit tests where everything but your code has to be mocked and only supports classes
* KernelTestBase, which provide a basic in-memory drupal environment. Much faster than browser tests but more tedious to set up, you have to explicitly install tables you need and depend on all modules you need explicitly
* BrowserTestBase, the replacement for WebTestBase, better apis (uses mink and so on) but just as slow.
* JavaScriptTestBase, phantomjs based JS tests, even slower but can actually execute JS.
> 7 votes

# Answer
What you are probably looking for is Kernel Test base. You can already create nodes and terms there if you want to, and it still can be fast (3-6 seconds).

In Unit test you only test your class and mock the rest, you can't really make real entity instances.
> 1 votes

---
Tags: 8, testing
---


# Question
Title: When to use a php function vs a drupal_ equivalent function?
I come from update my Coder module to the v1.3 and when I go to check one custom module I see the following message:

> Line 71: in most cases, replace the string function with the drupal\_ equivalent string functions
>
> ```
> $node_type = substr($form_id, 0, -10);
>
> ```
>
> Line 187: in most cases, replace the string function with the drupal\_ equivalent string functions
>
> ```
> $info->language = ($info->language == 'und' || empty($info->language)) ? t('Undetermined') : ucfirst($info->language);
>
> ```

So, why I need to use the drupal\_substr() and drupal\_ucfirst() in this case? And in general why to use the drupal\_ equivalent functions when we have the php functions?

# Answer
> 4 votes
Most PHP string function don't handle unicode characters. For this you need to use their `mb_*` variants, which are (were?) not always available on some host. The `drupal_*` variants ensure unicode compatibility. They wrap `mb_*` functions and provide pure PHP implementations for when they are not available.

So, this recommendation is there to ensure portability of your code across hosts.

---
Tags: 7, coding-standards
---


# Question
Title: How does apache solr search recognize my changes by mysql query in my database
I would like to use mysql query to modify some of my data. But I found that apache solr doesn't index all my changes.

For example, I modified some products' category in the field\_data\_field\_category table through query yesterday. When I went to those products' content edit page, the category shows correctly. However, I found that Apache Solr doesn't count any of them into Remaining Item.

Does anyone know how does apache solr search work? Or what kind of query I should use to achieve my goal.

# Answer
> 2 votes
Solr maintains in own search index separated from the database. A process is required to index content from your database into Solr's index. Usually, this is done transparently by the Drupal Solr integration modules. These integrtions rely on usage of Drupal API for content changes. These API allow integration code to be executed on changes. This code will either index the change directly, or mark the content for re-indexation during the next cron run.

By accessing the database directly, you bypass Durpal's APIs and prevent the integration module to see your changes.

If this is a one off operation, you should be able to mark all content for re-indexation from the administration page of your Solr integration module.

---
Tags: 7, database, search
---


# Question
Title: I need to add on condition to profile form submit handler profile2_form_submit_handler
I need to add on condition to profile form submit handler. I have wrote the condition to **profile2\_form\_submit\_handler function** which is found under `sites/all/modules/profile2/profile2.module` location.
I have applied the condition in core file but now wanted to move this set of core to template.php file but it is not reflating.
Anyone please suggest me to make it from hook or something other.
My code is:

```
function THEMENAME_form_submit_handler(&$form, &$form_state) {
  profile2_form_submit_build_profile($form, $form_state);
  // This is needed as some submit callbacks like user_register_submit() rely on
  // clean form values.
  profile2_form_submit_cleanup($form, $form_state);

  foreach ($form_state['profiles'] as $type => $profile) {
    // During registration set the uid field of the newly created user.
    if (empty($profile->uid) && isset($form_state['user']->uid)) {
      $profile->uid = $form_state['user']->uid;
    }

    // check default image status
    // if there is not any then make first image as default
    $default = false;
    $images = $profile->field_user_image['und'];

    foreach($images as $image) {
        if(($image['field_profile_default']['und'][0]['value'] == 1)
         &&($image['entity']->field_profile_default['und'][0]['value'] == 1)) {
            $default = true;
            break;
        }
    }

    profile2_save($profile);
  }
}

```

# Answer
A theme can not simply override a form handler. What you need is a form alter function (`hook_form_FROM_ID_alter()`) to alter the profile2 form, remove its original submit handler and replace it with your own.

```
THEMENAME_form_profile2_form_alter(&$form, &$form_state) {
  array_splice($form['#submit'], array_search('profile2_form_submit_handler', $form['#submit']), 1, 'THEMENAME_form_submit_handler');
}

```

Because your are changing the behavior of your site, this should be implemented in a custom module rather than in the theme. Themes are about presentation.

Also, instead of altering profiles on form submit, you could also implement `hook_profile2_presave()` to alter the profiles before they are saved to the database, regardless on how they are created (ie. your code will also work for profile created programmatically).
> 0 votes

---
Tags: 7, users
---


# Question
Title: altering a block that is embedded in a view
I have a view and in the header of the view, I am rendering a custom block. The block is showing up just fine, however, I need to alter it and I cannot seem to figure this out. I have tried `hook_preprocess_block`, `hook_block_view_alter` and a couple others. I know the ID of my block but it isn't helping.

If I am embedding the block in the view and I want to alter the block, do I need to first alter the view and tell it to rerender the block? I am using drupal 8. Any help would be appreciated.

# Answer
> 5 votes
I assume you're displaying a block\_content entity.

That is not actually rendered through the block system, it's an entity, so you need to implement hook\_block\_content\_view() (see hook\_ENTITY\_TYPE\_view() for documentation)

---
Tags: 8, blocks
---


title: Drush Jailed by Jailshell

text:
# Question
Title: Drush Jailed by Jailshell
My web host (Bluehost) recently switched shell access from bash to Jailshell. That simple switch has sent Drush on vacation. It has been months and the host has not been able to find a solution (or isn't looking). Below are a couple of error messages returned from `drush status`. The problem isn't the PHP version. The problem is Jailshell.

> Parse error: syntax error, unexpected T\_STRING, expecting T\_CONSTANT\_ENCAPSED\_STRING or '(' in /home2/username/.composer/vendor/drush/drush/includes/preflight.inc on line 8 user@domain.com \[~/public\_html/clientfolder\]# drush status
>
> Warning: Unexpected character in input: '\\' (ASCII=92) state=1 in /home2/username/.composer/vendor/composer/autoload\_real.php on line 23
>
> Parse error: syntax error, unexpected T\_STRING in /home2/username/.composer/vendor/composer/autoload\_real.php on line 23

Any assistance would be greatly appreciated. Thank you.

# Answer
There's no assistance available, really, this is out of your hands and can only be fixed by the server admins.

Your three options are:

1. Convince your hosting provider to upgrade the version of PHP you have available in the shell. If they tell you they don't know how to do that, go to option 3.
2. Downgrade drush to something that works with old versions of php
3. Change your hosting provider to one who's got their act together. Your current provider hasn't, clearly.
> 2 votes

# Answer
I am currently experiencing this same problem on some of the accounts on Bluehost that I manage for my clients. Currently, tech support at BH is unable to provide a solution. Clive suggested asking BH to upgrade PHP, but that's not the issue. Until now, you could call any version of PHP you wanted in your bash script. I had mine set up to call PHP 5.4 to run both composer and Drush. That doesn't work now, and BH currently doesn't have a solution.

Clive also suggested downgrading Drush, but that's not a solution either. I've tried that. The problem is that Bluehost replaced their normal shell interface with jailshell, a very restrictive version of shell that won't allow Drush to operate. Period. The only solution I see as being currently viable at the moment is to change hosts. We are exploring that option now.
> 0 votes

---
Tags: drush
---


# Question
Title: modify submit on user login so that only admins can log in through this route
I have written a hook form alter which adds a submit action but I get this error

> Recoverable fatal error: Argument 2 passed to xxx\_form\_submit() must be an instance of FormStateInterface, instance of Drupal\Core\Form\FormState given in xxx\_form\_submit()

the code is like this

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

 if ($form_id=='user_login_form') {

    $form['actions']['submit']['#submit'][] = 'xxx_form_submit';
  }
}

function xxx_form_submit ($form, FormStateInterface  $form_state) {
  $username=$form_state->getValue('name'));
}

```

# Answer
> 4 votes
You are getting this because you did not include the use statement at the top of your file:

```
use Drupal\Core\Form\FormStateInterface;

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

 if ($form_id=='user_login_form') {

    $form['actions']['submit']['#submit'][] = 'xxx_form_submit';
  }
}

```

You can use the full path, but it is preferred for developers to do `use` statements.

# Answer
> 0 votes
I had to put the whole path of the formstateinterface into the submit function \Drupal\Core\Form\FormStateInterface

---
Tags: 8, forms
---


# Question
Title: enable/disable node_save programmatically
I created a custom module that can save nodes.

I want a checkbox that determines whether the node will be saved or not.

This is the node\_save program :

```
     global $user;

// IF (FORM_STATE [VALUE][CHECKBOX] == Checked ! ) {

        $node = new stdClass();
        $node->type = "services";
        node_object_prepare($node);
        $node->language = 'fr'; // Or e.g. 'en' if locale is enabled
        $node->uid = $user->uid;
        $node->status = 1; //(1 or 0): published or not
        $node->promote = 0; //(1 or 0): promoted to front page
        $node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
        $node->title = $form_state['values']['produit_de_client'];

        $node->field_produit_dc['und'][0]['value'] = $produit;
          $node->field_espace_dediee_categories[LANGUAGE_NONE][0]['tid']=$form_state['values']['espace_dediee'];

        $node->body['und'][0]['value'] =$form_state['values']['text_service'];
        $node->body['und'][0]['format'] ='full_html';

        $aaz= array_filter($form_state['values']['wrapperrr']['id_offre']);
     foreach($aaz as $of)
       {

       $node->field_offre[LANGUAGE_NONE][]['target_id'] = $of;

       }

        $node->field_id_prod['und'][0]['value'] = $produit;
            $file = file_load($form_state['values']['image_dc']);
            $file->status = FILE_STATUS_PERMANENT;

            $uploaded = file_save($file);
            $aaa = file_create_url($file->uri);
        $node->field_produit_dc['und'][0]['value'] = $file->fid;
        $url = $file->uri;

        $node->field_image_serv[LANGUAGE_NONE][0]['fid'] = $file->fid;

        node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().

        $node = node_submit($node); // Prepare node for saving
        node_save($node);

//ELSE NO NODE WILL BE SAVED

```

# Answer
In a nutshell:

```
function mymodule_form_submit($form, &$form_state) {
  if ($form_state['values']['mycheckbox'] == 1) {
    // node code...
    node_save($node);
    drupal_set_message('Node saved.');
    $form_state['redirect'] = 'some/path';
  }
}

```

Or you could just require the checkbox in the form:

```
$form['mycheckbox'] = [
  // props
  '#required' => TRUE,
];

```

If the checkbox is required, the form can't be submitted, and thus the node won't be created.

I would probably require the field(s) instead of silently do nothing on submit if they did not check it. That way the form submit won't get hit and the user won't have to re-enter all of the information.
> 1 votes

---
Tags: 7, nodes, forms, hooks
---


# Question
Title: Using reverse proxy prevent login flooding
I have set `$conf['reverse_proxy'] = TRUE;` in settings.php, but the IP address logged in the flood table is 127.0.0.1, not the one passed through the X-Forwarded-For header. Nginx is configured to send the X-Forwarded-For header to Apache, but it seems Drupal isn't recognizing it.

This is pretty bad because a few failed logins can lockout for everyone.

How can I make Drupal use the IP passed within the X-Forwarded-For header?

# Answer
I had to edit the `$conf['reverse_proxy_addresses'] = array('a.b.c.d', ...);` part, and put in the address of reverse proxy address (127.0.0.1).
> 1 votes

# Answer
In settings.php, set options and put your proxy IP.

```
// Reverse proxy support to make sure the real IP gets logged by Drupal.
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
$conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';

```
> 1 votes

---
Tags: 7, proxies
---


# Question
Title: How to modify .htaccess to serve brotli compressed static assets over gziped ones?
I'm trying to use brotli compressed static assets with Advanced CSS/JS Aggregation as detailed here, https://www.drupal.org/node/2773807. The assets are created as they should be, but they're never served because the .htaccess file doesn't know to do that.

lyncd.com has a short walkthrough, https://lyncd.com/2015/11/brotli-support-apache/, but I haven't been able to munge their code into Drupal's.

Here' the lyncd.com example:

```
    FileETag None

    <Files *.js.gz>
      AddType "text/javascript" .gz
      AddEncoding gzip .gz
    </Files>
    <Files *.css.gz>
      AddType "text/css" .gz
      AddEncoding gzip .gz
    </Files>

    <Files *.js.br>
      AddType "text/javascript" .br
      AddEncoding br .br
    </Files>
    <Files *.css.br>
      AddType "text/css" .br
      AddEncoding br .br
    </Files>

    RewriteEngine On

    RewriteCond %{HTTP:Accept-Encoding} br
    RewriteCond %{REQUEST_FILENAME}.br -f
    RewriteRule ^(.*)$ $1.br [L]

    RewriteCond %{HTTP:Accept-Encoding} gzip
    RewriteCond %{REQUEST_FILENAME}.gz -f
    RewriteRule ^(.*)$ $1.gz [L]

```

And here's the 7.50 .htaccess bit:

```
    # Rules to correctly serve gzip compressed CSS and JS files.
    # Requires both mod_rewrite and mod_headers to be enabled.
    <IfModule mod_headers.c>
      # Serve gzip compressed CSS files if they exist and the client accepts gzip.
      RewriteCond %{HTTP:Accept-encoding} gzip
      RewriteCond %{REQUEST_FILENAME}\.gz -s
      RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

      # Serve gzip compressed JS files if they exist and the client accepts gzip.
      RewriteCond %{HTTP:Accept-encoding} gzip
      RewriteCond %{REQUEST_FILENAME}\.gz -s
      RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

      # Serve correct content types, and prevent mod_deflate double gzip.
      RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
      RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

      <FilesMatch "(\.js\.gz|\.css\.gz)$">
        # Serve correct encoding type.
        Header set Content-Encoding gzip
        # Force proxies to cache gzipped & non-gzipped css/js files separately.
        Header append Vary Accept-Encoding
      </FilesMatch>
    </IfModule>

```

With your powers combined we can make the web about 20% cooler!

# Answer
> 7 votes
Give this a try

```
# Rules to correctly serve gzip compressed CSS and JS files.
# Requires both mod_rewrite and mod_headers to be enabled.
<IfModule mod_headers.c>
  # Serve brotli compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} br
  RewriteCond %{REQUEST_FILENAME}\.br -s
  RewriteRule ^(.*)\.css $1\.css\.br [QSA]

  # Serve gzip compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

  # Serve brotli compressed JS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} br
  RewriteCond %{REQUEST_FILENAME}\.br -s
  RewriteRule ^(.*)\.js $1\.js\.br [QSA]

  # Serve gzip compressed JS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

  # Serve correct content types, and prevent mod_deflate double gzip.
  RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
  RewriteRule \.css\.br$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.br$ - [T=text/javascript,E=no-gzip:1]

  <FilesMatch "(\.js\.gz|\.css\.gz)$">
    # Serve correct encoding type.
    Header set Content-Encoding gzip
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
  <FilesMatch "(\.js\.br|\.css\.br)$">
    # Serve correct encoding type.
    Header set Content-Encoding br
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
</IfModule>

```

---
Tags: 7, performance, .htaccess
---


title: Waiting for table metadata lock

text:
# Question
Title: Waiting for table metadata lock
getting lock messages as.... “Waiting for table metadata lock” occurs in database whenever there is “truncate cache\_entity\_node” call execute.

How can we disable truncate action on entitycache module ?

We are having issues with “metadata locks” with the DB so performance continue to be an issue here.

# Answer
> 2 votes
The locking issue is likely related to your database type and configs.

But you definitely do want to keep the truncate operation. To explain why, here is an order of operations on Entity CRUD in the entitycache.module. For example, on Entity update:

* `entitycache_entity_update()` (an implementation of `hook_entity_update()`) is invoked
* Skipping the condition check for a moment, `cache_clear_all($id, 'cache_entity_' . $type);` fires, and it seems your Entity type is `node` (hence why `cache_entity_node` cache bin is cleared. You want this, otherwise you will get stale data.
* `cache_clear_all` in turn calls `_cache_get_object($bin)->clear($cid, $wildcard);`, and if for example your cache backend is the default cache implementation, this will call `DrupalDatabaseCache::clear`, which in turn will likely call `db_truncate()`
* `db_truncate()` calls `Database::getConnection($options['target'])->truncate($table, $options);`, and that returns the `TruncateQuery` class
* This is just so you can try to do these traces yourself, if you haven't already (or someone else reading can do this).
* Skip to `TruncateQuery::__toString()`. If there is a transaction in progress, the SQL is `'DELETE FROM {'` (and if not it's `'TRUNCATE {'` (which is much faster). It sounds like you have a transaction in progress, and so you definitely want a row-by-row deletion with locks during (so it can roll back on failure if needed, whereas `TRUNCATE` is destructive). If you have many rows, depending on your database configs, this could possibly lock the entire table, not just the rows in question during the operation.

If this is the case, you can try various things to resolve it (caveat: you really want to contract a DBA or someone who knows your infrastructure and database setup very well). But for example, let's say your database type is MySQL: you could try reducing the lock wait timeout from the default. You could also try to change the transaction isolation level (preferable to READ COMMITTED). You'll want to read closely the comments above the `$databases` array in default.settings.php, specifically `init_commands` (issued for each connection which allow sessions settings to persist – you can set `lock_wait_timeout` and `transaction_isolation` here). There are various references to this, like Use READ COMMITTED for MySQL transactions core issue (for 8.x now, was for 7.x initially).

There is no single answer to this question, because like I said it very much depends on your setup. But I hope this gives you some direction toward solving your locking issue.

## Update

Based on the issue tied to the patch your comment, I am adding more info to my answer:

Looking over Waiting for table metadata lock on cache\_field table, the earlier patch in #3 gave way to an updated patch in #26. However, if you read all the information, in the end it looks like your best bet is to either 1. Not use entitycache module with DB cache backend (as Fabianx said - then again, I have experienced a similar issue using memcache so, again depending on your DB configs YMMV), or 2. try out the Asynchronous Prefetch Database Query Cache module that @mikeytown2 created to resolve this issue.

---
Tags: database
---


# Question
Title: Media library duplicating results view in ckeditor
After numerous problems on a certain website I tried a bare bones fresh install of drupal 7.5 on a subdomain with nothing but the medial library and its dependencies as well as all modules required to put the media library in the CKeditor and what I got was a brand new media library failure not yet seen...

Anyone know why the modal popup repeats the results view multiple times? 3 to be exact but you can only see 2 in this image. I followed the instructions on all components to get this far but the never ending failure of drupal continues to plague me.

**update**

I hadn't noticed before because of the baffling behavior, but it turns out I can't even select media from any of these repeating views. If I click one and hit submit it just returns me to the node, not updated. Right inside the modal box.

Another note, the views for media library include 3 different views - "media browser" "my files" and "media library" and if I disable any of them they do indeed disappear from the popup, which I could live with if any of the remaining views actually did anything. I applaud the champions who wrote this.

**Final Update**

With Kevin's help we figured it out. Basically we had to run with wysiwyg module, and use the manual install of ckeditor v 3.5.3 - between those 2 and all the configurations standard to drupal the wysiwyg media library finally works. I guess this makes sense since drupal 8 came out some people may have just not cared to keep the 7x modules stable. Or maybe I'm an idiot and following the step by step instructions on the latest media library module for 7x was just too complicated... but for all of us stuck in the nightmare of drupal, here's one option.

# Answer
This is a shot in the dark, but are you running jQuery Update module? If not, you should give it a try and set the admin area to use jQuery 1.7. Drupal 7 core shipped with jQuery 1.4, and some modules evolved to needing a newer version of jQuery. jQuery Update will solve that for you.

https://www.drupal.org/project/jquery\_update
> 0 votes

---
Tags: 7, views, wysiwyg, media
---


title: Drupal 7 Views Isotope Error

text:
# Question
Title: Drupal 7 Views Isotope Error
I have an ecommerce site using the module views isotope to display the product grid. After a recent upgrade, It looks like my view is broken and I'm getting this warning:

> "Warning: in\_array() expects parameter 2 to be array, string given in ...(my theme directory)".

The warning can be viewed here: http://biltriteinc.com/?q=supports

What is causing the error?

# Answer
> 0 votes
Error is as stated..

```
Warning: in_array() expects parameter 2 to be array, string given in goodnex_item_list() (line 212 of /home/biltrite/public_html/sites/all/themes/goodnex/template.php)

```

Whatever is calling `in_array` in `goodnex_item_list` is not passing an array as the second argument and instead is passing a string. You'll have to backtrack from there to figure out what and why.

See: in\_array

---
Tags: 7, views, theming
---


# Question
Title: How can I show the field setting options like "Style Settings", "Rewrite Results" in Views
I created a view and added some fields, I saw others can configure field options like "Style settings" and "Rewrite Results", but in my "Configure Field:" window, I don't have these options, only several blank rectangles. See below image,

Is there any settings I missed or any new modules I didn't installed?

# Answer
> 0 votes
Eventually I realized it's a web browser issue. I was using Google Chrome and the options are hidden by some "injected stylesheet", see following screenshot,

And I change to use IE, it works fine (jQuery version 1.10 is fine also), all these options are showing properly.

# Answer
> 0 votes
It's a jQuery issue. Downgrade to 1.5 for administrative pages only (admin/config/development/jquery\_update). Greater versions break views and other admin areas - not sure why though

---
Tags: 7, views
---