# Question
Title: How to fix error: Failed to load resource: the server responded with a status of 404
I have a repo mirrored from `https://github.com/drupal/drupal.git` and integrate it in OpenShift web server.

I did a regular installation with the dev site OpenShift URL. It installs successfully but the site is broken. I'm signed in as admin but getting a no theme page with just text on it. Supposedly, it should generates all needed files and folders.

When I access my web server, I check this errors:

I have already change the folder `files` permission to 777 from 775. These files is not generating on the folder.

This is the content of my .htaccess file.

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
  </IfModule>
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Add correct encoding for SVGZ.
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

# Most of the following PHP settings cannot be changed at runtime. See
# sites/default/default.settings.php and
# Drupal\Core\DrupalKernel::bootEnvironment() for settings that can be
# changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value assert.active                   0
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
  # PHP 5.6 has deprecated $HTTP_RAW_POST_DATA and produces warnings if this is
  # not set.
  php_value always_populate_raw_post_data   -1
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Set a fallback resource if mod_rewrite is not enabled. This allows Drupal to
# work without clean URLs. This requires Apache version >= 2.2.16. If Drupal is
# not accessed by the top level URL (i.e.: http://example.com/drupal/ instead of
# http://example.com/), the path to index.php will need to be adjusted.
<IfModule !mod_rewrite.c>
  FallbackResource /index.php
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\.(?!well-known)" - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

  # 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>
</IfModule>

# Various header fixes.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
  # Disable Proxy header, since it's an attack vector.
  RequestHeader unset Proxy
</IfModule>

```

# Answer
Permission is one thing, but is the folder actually *writable*? Ony many such services, the file system is often by default read-only as it is meant to be shared across multiple nodes. You need to set up and configure a shared, writable file system.

How exactly you need to do that is an Openshift specific question that is better answered elsewhere.

Found https://hub.openshift.com/quickstarts/24-drupal-8 with a bit of googling, that sets up the data dir and symlinks for the files. Actually seems to be a bit outdated, but should still give you the general idea.

You can also disable CSS/JS aggregation, see example.settings.local.php but that's only for testing and you will need that once you want to upload images or so.
> 3 votes

# Answer
Its late to answer though but might be helpful for someone. Openshift old platform doesn't support PHP 5.6 and I believe, PHP 5.6 is needed for D8? I faced similar issue while working on a D8 site. Thus I created one quickstart myself. Please have a look, this might come handy.

REPO: https://github.com/aneek/nginx-php-drupal8-quickstart

WIKI: https://github.com/aneek/nginx-php-drupal8-quickstart/wiki/Installation-Instruction
> 1 votes

---
Tags: 8
---


# Question
Title: How to create a search box bloc with search API
I'm using Drupal 8 and i've installed search API and Search API Solr Search.

I followed this great tutorial

How can I display a search box on all of the pages of my website ?

# Answer
Since search api uses Views to create the page, you can use Views to also create a search block. There are many ways to do such a thing with views. The simplest is to output the exposed form as a block (advanced settings).
> 1 votes

# Answer
Although you can expose the views form as a block and you can add it twice to a page, the issue is that you may just want a keyword search form in the header but on the actual form you want something more. An additional peculiarity was that the infinite scrolling plugin makes the form ajax, and when exposed as a block it fails to submit.

My solution was to create a new form + block and place the block it where I needed it:

**my\_search.module:**

```
<?php
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() for the search_block_form form.
 */
function my_search_form_header_search_alter(&$form, FormStateInterface $form_state) {
  // NB so that these are not added to the get query params
  $form['form_build_id']['#access'] = FALSE;
  $form['form_token']['#access'] = FALSE;
  $form['form_id']['#access'] = FALSE;
}

```

**HeaderSearch.php:**

```
<?php

namespace Drupal\my_search\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class HeaderSearch.
 *
 * @package Drupal\my_search\Form
 */
class HeaderSearch extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'header_search';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#action'] = '/search';
    $form['#method'] = 'get';
    $form['k'] = [
      '#type' => 'search',
      '#title' => $this->t('Keyword'),
      '#maxlength' => 64,
      '#size' => 15,
      '#title_display' => 'invisible',
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      // Prevent op from showing up in the query string.
      '#name' => '',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Form is redirected no need for anything here.
  }
}

```

**MySearchBlock.php:**

```
<?php

namespace Drupal\my_search\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'MySearchBlock' block.
 */
class MySearchBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\my_search\Form\HeaderSearch');
  }

}

```
> 4 votes

---
Tags: search
---


# Question
Title: Core listed as outdated, but composer is not updating it
I'm facing a strange issue with drupal-composer.
It has been installed via the usual command line:

```
$ composer create-project drupal-composer/drupal-project:8.x-dev ./ --stability dev --no-interaction

```

Now I want to update `drupal/core`, and here's what I've got:

```
$ composer show -l
[...]
drupal/core  8.3.1  8.3.3  Drupal is an open source content management platform powering millions of websites and applications.

$ composer update drupal/core --with-dependencies
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

```

I've maintained Drupal instances with Composer for monthes, and never faced this kind of issue (other instances have successfully been updated to 8.3.2 or 8.3.3).
I've tried to clear Drupal and Composer caches, and desperately ran `/update.php` before another try, without luck.

Any thoughts?

# Answer
Eventually, I fixed this issue running a global:

```
composer update

```

Still don't understand what was blocking me from updating `drupal/core`.
> 0 votes

# Answer
You can use Drush commands to update the drupal code.

```
drush up

```
> 0 votes

---
Tags: 8, updating, composer
---


# Question
Title: How to change a views block ID attribute to use it as anchor
I have a views block with `id=block-views-block-services-block-1` which I used in the menu link.

The menu link is now shown as https://example.com/gb/#block-views-block-services-block-1

As you can see it's really not looking nice with long hyphend words. Is there any easy way to change it to something like this https://example.com/gb/#services

I read an answer for Drupal 7 where we need to edit `template.php` to change the ID. But in Drupal 8 it seems that `template.php` is replaced with `twig.html`. I'm not very sure as I'm new to Drupal.

Could anyone please explain few steps on how to do it?

# Answer
you should place this function in your `themes/YOURTHEME/YOURTHEME.theme` file:

```
function YOURTHEME_preprocess_block(&$variables) {
  dump($variables);
}

```

and you will see the name of your block. You have to look for `block_html_id`. Based on your description the value of the `block_html_id` will be `block-views-block-services-block-1`.

Then you can simply owerdefine it this way:

```
function YOURTHEME_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-views-block-services-block-1") {
    $variables['block_html_id'] = "services";
  }
}

```

Or you can create a custom module and you can put this function there too. In that case you have to replace the `YOURTHEME` to the name of the custom module.
> 2 votes

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


# Question
Title: receiving incorrect url from amazon s3 module
I am using drupal 7. I have installed amazon s3 module and its dependencies. I have created a bucket for saving my files on amazon server. Everything went good.. But when i try to get the path for the file it looks like this

http://bucketname.s3.amazonaws.com/abc.pdf

Later i came to know the actual path must look like https://s3.amazonaws.com/bucketname/abc.pdf

As a result i am unable to access the pdf. It always shows access Denied as a response.

Please help me to over come this.

# Answer
> 0 votes
You need to create a group permission for Amazon S3 in Amazon IAM and indicate who can view the bucket.

Instructions on how to grant access to your bucket here: http://blogs.aws.amazon.com/security/post/Tx3VRSWZ6B3SHAV/Writing-IAM-Policies-How-to-grant-access-to-an-Amazon-S3-bucket

Hope this helps.

# Answer
> 0 votes
Drupal generates image caches on view, not on create/update.

When you try to hit a image that does not exists, Amazon responds you are not allowed to.

Amazon should be able to use a failover or "origin" server, to work in the "pull" instead of the "pull" mode. I have been in the phone with a couple aws reps, and they do not understand what I want, nor leave me talk with the next tech level.

For me the solution is to make image caches being generated on save, like making a simple hook or install something like imageinfo cache https://www.drupal.org/project/imageinfo\_cache

# Answer
> 0 votes
The following patterns are valid for constructing S3 URLs: http(s)://.s3.amazonaws.com/ http(s)://s3.amazonaws.com//

After you need to create user and group and set permission at Amazon s3.

Pls browse your bucket, select the s3fs-public folder and choose Actions - Make Public.

---
Tags: 7
---


# Question
Title: Extend an existing Views filter (NumericFilter) throws exception
I am trying to do something that should be easy in Views but I can't seem to be able to make it work.

I need to create a filter on top of the existing `NumericFilter` (`Drupal\views\Plugin\views\filter\NumericFilter`), but with a minimalistic approach like the following it is simply not working.

```
<?php
// @file src/Plugin/views/filter/FoobarProjectSizeRangeSelectionFilter.php

namespace Drupal\foobar_extra\Plugin\views\filter;
use Drupal\views\Plugin\views\filter\NumericFilter;
/**
 * Class DateYearFilter
 * @ingroup views_filter_handlers
 * @ViewsFilter("project_size_range_select")
 */
class FoobarProjectSizeRangeSelectionFilter extends NumericFilter {
}

```

The way I use is is pretty straight forward:

```
<?php
// @file foobar.views.php
/**
 * Implements hook_views_data_alter().
 */
function foobar_views_data_alter(array &$data) {
  // clone an existing field
  $data['node__field_a']['field_a_value_range'] = $data['node__field_a']['field_a_value'];
  // change name and filter ID
  $data['node__field_a']['field_a_value_range']['title'] = t("Foobar");
  $data['node__field_a']['field_a_value_range']['filter']['id'] = 'project_size_range_select';

  return $data;
}

```

Whenever I try to save a view using this filter plugin i get the following error:

> ```
> InvalidArgumentException:
>  The configuration property display.default.display_options.filters.field_a_value_range.value.min doesn't exist.
>  in Drupal\Core\Config\Schema\ArrayElement->get()
>  (line 74 of ROOT/web/core/lib/Drupal/Core/Config/Schema/ArrayElement.php).
>
> ```

Right now I have "worked around it" implementing some custom and terrible hacks, but i'm pretty sure this is so simple that it should just work.

# Answer
> 10 votes
So, yeah I ended up investigating more and more and I needed to specify a config schema definition as it follows.

```
# @file config/schema/foobar.views.schema.yml
#
# Schema for the views plugins.

views.filter.project_size_range_select:
  type: views_filter
  label: 'Foobar numeric'

views.filter_value.project_size_range_select:
  type: views.filter_value.numeric
  label: 'Foobar Numeric'

```

The full gist is available here if anyone is interested.

---
Tags: 8, views
---


# Question
Title: How do I get the user ID for the currently logged-in user?
I want to get current user object (user information) in Drupal 8.

I know in Drupal 7 there was a global `$user` variable; I want to know how I can get current user object in Drupal 8.

# Answer
> 65 votes
```
$user = \Drupal::currentUser();

```

See the `Drupal` class. There are a lot of helper methods; most of them are shortcuts for services, so you don't have to call `\Drupal::service()` directly.

Note that the current user is not the user entity, it is just user proxy. You can get some basic information from it but fields or other entity-specific logic is not present. To access the user entity you have to load it manually:

```
$user = User::load(\Drupal::currentUser()->id());

```

Unfortunately **there is no** direct method like `\Drupal::currentUser()->getEntity()` :(

# Answer
> 29 votes
Example of how to ***load current user*** and ***retrieve field data*** from user object.

```
<?php
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// retrieve field data from that user
$website = $user->get('field_website')->value;
$body = $user->get('body')->value;

$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;
?>

```

# Answer
> 25 votes
Accessing methods on the `\Drupal` global class (like `::currentUser()`) is OK in procedural code (e.g. in your `mymodule.module` file) but in your own OO code you should try to access the `@current_user` service, via a standard pattern called dependency injection (DI):

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\Session\AccountProxyInterface;

class MyClass {
  /**
   * @var AccountProxy
   */
  protected $currentUser;

  public function __construct(AccountProxyInterface $currentUser) {
    $this->currentUser = $currentUser;
  }

  public function doSomething() {
    $currentUserId = $this->currentUser->id();
    /* ... */
  }
}

```

This pattern permits your code to be tested in complete isolation, with a dummy `$currentUser` object (anything which implements `AccountProxyInterface`, and can hugely reduce maintenance overheads.

However, DI isn't very intuitive and takes a while to understand. How you get the service into your object constructor depends on what the object actually is in Drupal e.g. plugins behave differently from registered services. There's more information on DI in Drupal 8 in the d.o docs.

\[edit\] A suggested edit to this answer (which was rejected by moderators) introduced `public static function create()` into the code, with no further explanation. However, it'd be misleading to add this class method without any further discussion.

For reference, this is what the create() function would look like:

```
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

```

The class method is *not* used by any services you register via a module's `mymodule.services.yml`: for these, the container calls the constructor directly. It's only ever useful for injecting into non-service classes; for example:

* creating a custom form: you must declare you implement `ContainerInjectionInterface` so that the container knows to look for `::create()`.
* creating a Drupal Plugin, using the wider Plugin architecture: you must declare you implement `ContainerFactoryPluginInterface`, which demands a different method signature for `::create()`.

This isn't the place to expand too much on dependency injection, but further information about the `::create()` method is available on this blogpost.

---
Tags: users, 8
---


# Question
Title: Fresh drupal install shows drupal core warning
I recently installed drupal using git clone option and updated it using composer but I am getting this error I can't fix.

Is there any way to fix this issue? clicking on available updates won't fix the issue. Also, the error related with "LIMITED DATE RANGE" seems mistaken, because I have php7 installed on a 64bit system

# Answer
> 0 votes
Since you used git clone, you probably pulled from the HEAD and are running a development version of Drupal. Your Drupal installation does not have an official version number, so it cannot be detected. You can install Drupal with composer, download the zip, or try to clone a tagged release (I always used composer so I am not sure if a tagged release works).

As for the 32/64 bit warning. Depending on the PHP version you have installed, you can run a 32bit PHP installation on a 64bit OS. I suppose that is the root of your problem.

---
Tags: datetime, installation
---


title: Submit package to packagist.org

text:
# Question
Title: Submit package to packagist.org
I'm trying to submit a module to packagist.org so that it can be directly installed via `composer`. I've followed the necessary steps and created the composer.json as required. Now when I'm trying to submit the module to packagist.org its giving me the following error:

> The vendor is already taken by someone else. You may ask them to add your package and give you maintainership access. If they add you as a maintainer on any package in that vendor namespace, you will then be able to add new packages in that namespace. The packages already in that vendor namespace can be found at drupal

# Answer
> 1 votes
You should not put your Drupal modules on packagist.org. Drupal modules are available on packages.drupal.org, where the module will be automatically exposed if you add it on Drupal.org.

it is explained here: Using packages.drupal.org.

---
Tags: 8, composer
---


# Question
Title: Render multiple taxonomy term input as unordered list
We have a content type allowing input from taxonomy term lists, and some fields allow multiple values. When there are multiple values, the output always seems to string them together inline, as much as will fit the available display width. We are aware of the option "separated" with the option of commas, spaces, or slashes, but that still renders multiple terms on the same line if they fit.

What's desired is to render multiple terms in a one-item-per-line list, preferably an unordered list with or without bullets. I tried looking at the CSS but all I could do was to add bullets, although it still rendered multiple terms inline. Suggestions? Thanks.

# Answer
This may not fit your need exactly, but did you know that the Separator in the 'Multiple field settings' accepts html?

That means that you could use "`<br />`" as the separator, and they'll render on different lines, even if they are not in a list.

Would that be enough for your needs or do you need a list?

====================== Edit based on comments =======

Maybe just a simple css rule added to your theme then that places the break there for you:

```
.your-content-type .your-field-class a {
    display: block;
}

```

It looks, based on your comments, that the above example may be something like this for you:

```
.node-content-type .field-name-field-client a {
        display: block;
}

```

That should do it for you. The 'block' (vs inline) display will put each link on a separate line. If you do that, you can remove all the commas and other separators, or those will appear on separate lines too (because of the block display of the link).

\** Note: I added one more selector (**the content type selector**) to make this rule even more specific. Based on the rule above, this 'display: block' property will be applied only to nodes of this specific content type (so if you use this tag somewhere else, they won't just come out on separate lines unexpectedly). Does that make sense?

To find what the content-type class for your node is, look into the page source again and find the line that looks like this:

```
<div id="node-62828" class="node node-content-type view-mode-full node-by-viewer clearfix">

```

The content type should be the second word in the class... in Drupal, all pages have the content type they belong to as a class, so that's awesome for theming!!

Finally, after changing your css, you may not see the result right away - you may need to clear your cache before your change will be applied.

Hope this helps!
> 1 votes

# Answer
You can always theme fields as you want - just use fields suggestion templates and wrap them as you want. The default field suggestion file should be named like field--machine\_name.tpl.php for D7 and single '-' for D6.

You can get more information for field templates at https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7

You can loop through all items in the $items\[\] array the field contains in the case of multi- value field and wrap them as it is required.

The theme template will work for field output throughout the system where field is rendered!

I hope this helps!
> 1 votes

# Answer
Getting back to this after several years! (Original motivation was my own desire to change the display, but eventually the client requested it.) Since Display Suite is being used in the display of the field items, the best solution was to enable DS "expert field templates," then enable the expert field template for just this one field item in the page, and apply DS configuration as shown in the screen capture; note that settings under "Manage Display" are significantly expanded due to enabling expert field templates:

This solution is based on an answer is this post: https://www.drupal.org/node/1141524 but my specific settings had to be a little different to accomplish the desired result.
> 0 votes

---
Tags: theming, entities
---


# Question
Title: Views with exposed filters WITHOUT `Use Ajax`?
Is there a way to use exposed filters, but not require `Use Ajax` ? I want exposed filters but I want it to submit the form and refresh the page.

# Answer
I believe you need to use the **Page Display**. That behavior doesn't work when the view is rendered as a block.
> 1 votes

---
Tags: 7, views
---


title: Custom fields always empty

text:
# Question
Title: Custom fields always empty
I followed the steps on skvare to index Civicrm contacts via Search API, then to have Views list the contacts with the search box as an exposed filter. This seems to work overall, but custom Civicrm fields don't seem to be showing up via Views. For example, I've got records showing up with display name, bio, and contact ID. But they're also supposed to have custom fields called "designation" and "role". I've checked that the corresponding contact created in Civi has values (strings "test" and "pencil sharpener" respectively) for these fields. I've made sure that these fields are indexed in the search API and I've rebuilt the search index, to no avail. I'm able to select the fields in the Views UI but when I look at my View, I don't see them and when I do a dump of the fields variable in the View template, those fields are there but they just have an empty value.

Why are my custom Civi field values empty when I try to display them on contacts indexed with the search API via Views? This is all in Drupal 7.

# Answer
Hard to confirm why yours are not showing. If I am comparing like with like then I have built some Views and used Search API to give the custom data in the View columns and to provide blocks showing the count for each of the sub-types of that custom data.

Thing is there is so many steps involved I don't really know how to provide a clear recipe for you to follow assuming of course that would be better thank Mark's since I know I used that as part of my own journey on this.
> 0 votes

# Answer
I solved this problem by making sure each field I wanted to use was an indexed field in the Search API settings for my Contacts index, and then re-adding the fields to Views.
> 0 votes

---
Tags: views, search, civicrm
---


# Question
Title: How to define Views filters and relationships for custom Civicrm contact fields that are indexed via Search API?
I followed the steps on skvare to index CiviCRM contacts via Search API, then to have Views list the contacts with the search box as an exposed filter.

I need to expose a filter that filters results based on what membership type the contact has. That might require a relationship, which is currently not an option in Views for me, so I might have to write a custom relationship handler as well as the custom filter handler. I have been trying to find the code to read to use as a guide but I have been unable to figure out whether these handlers are being defined in CiviCRM, Views, Search API, or the Civicrm Entity module which I'm also using.

How do you define a custom relationship and filter handlers for custom fields on CiviCRM contacts being displayed via Search API, CiviCRM Entity, and Views?

# Answer
If this is about getting Membership fields showing in the ADD RELATED FIELDS selector at the bottom of admin/config/search/search\_api/index//fields then I expect this is a civicrm entity issue in which case you could check at this chat channel

Otherwise you may be looking for sites/all/modules/civicrm/drupal/modules/views
> 1 votes

---
Tags: search, views, civicrm
---


title: CSRF token time life

text:
# Question
Title: CSRF token time life
I've get CSRF token from url /rest/session/token. After have CSRF token, I can send request (get, post) to API and working fine. But after time, when I send request. It's doesn't work. I'm getting error permission denies. I think maybe CSRF token expire time. So I want know time life of CSRF token. And how to change time life of CSRF token.

# Answer
This is the same question I had asked myself and I wanted to increase the lifetime to something like 6 hours.

However, the point behind CSRF tokens is that they change frequently so that nobody can try to steal one of those tokens and then use it to make a forged request. Here's the workflow I ended up using in my application:

* Request a CSRF token.
* Use the token to make requests.
* If the request fails because the token has expired, go to step 1.

Hope it helps. Happy coding.
> 3 votes

---
Tags: 8
---


# Question
Title: How output JSON for multiple "Rest export" views?
In Drupal 8, I'd like to retrieve JSON for multiple Rest export views, not just a single one. Example of data I want to see (cars and tires being two seperate content types):

```
{
    "cars": [
      { "nid": 1, "brand": "BMW", "weight": 100, "compatible_tire_nids": [100,101,102] },
      { "nid": 2, "brand": "Mazda", "weight": 100, "compatible_tire_nids": [102] },
      { "nid": 3, "brand": "Volvo", "weight": 1000, "compatible_tire_nids": [103] }
    ],
    "tires": [
      { "nid": 100, "brand": "Michelin" },
      { "nid": 101, "brand": "Good Year" },
      { "nid": 102, "brand": "Dunlop" }
    ]
}

```

I can output the JSON fine seperately, so you visit one url to get cars, and another URL to get tires. But I can't figure out how to merge the two.

Can anyone help me figure this out, or anyone who can point me in the right direction to achieve this?

# Answer
> 1 votes
One option would be to create a parent view and use Views Field View to reference the other 2 views displays.

For example, `/car-stuff` would contain 2 fields, "Cars" and "Tires", each one is a views field view field referencing the relevant json view display. For the parent view, you'd need to add REST Export Nested so the JSON of the child views would be proper JSON instead of a string.

**Alternative Solutions**

There may be a cleaner way to achieve what you're after.The easiest would be to make 2 calls to retrieve the JSON feeds and join them on the front end.

Depending on your requirements, you could also retrieve the specific tires for each car type.

```
{
    "cars": [
        { "nid": 1, "brand": "BMW", "weight": 100, "compatible_tire_nids": [100,101,102],
            "tires": [
              { "nid": 100, "brand": "Michelin" },
              { "nid": 101, "brand": "Good Year" },
              { "nid": 102, "brand": "Dunlop" }
            ]
        },
        { "nid": 2, "brand": "Mazda", "weight": 100, "compatible_tire_nids": [102],
            "tires": [
              { "nid": 102, "brand": "Dunlop" }
            ]
        },
        { "nid": 3, "brand": "Volvo", "weight": 1000, "compatible_tire_nids": [103],
            "tires": [
              { "nid": 103, "brand": "Unknown" }
            ]
        }
    ]
}

```

The above would also use Views Field View, with the child view `Tires` having a contextual filter of `nid`. For an example of this approach, see the answer I provided here.

---
Tags: views, 8
---


# Question
Title: How to get back the text formats like filtered_html, full_html or php_code for wysiwyg
I accidentally removed the text formats like:

* Full HTML
* Filtered HTML
* PHP Code

from admin \> config \> content authoring \> text formats.

I want to get them back but couldn't find a way. I re-installed the third party editor (ckeditor) for wysiwyg and also reinstalled the wysiwyg module, but it didn't help.

# Answer
> 3 votes
You soudln't disable text formats on config \> content authoring. Now you only can edit your site's database tables. Table "filter\_format" has column "status" and rows with text formats names. Change values in "status" column to 1 for each format you want be enabled.

# Answer
> 0 votes
For Drupal 8:

1. Export the configuration of the disabled filter
(under `/admin/config/development/configuration/single/export`)
2. Change the line `status: false` to `status: true`
3. Import the configuration
(under `/admin/config/development/configuration/single/import`)

After this, the previously disabled text filter will be listed under `/admin/config/content/formats` again.

---
Tags: 7, wysiwyg, input-formats
---


# Question
Title: How to appened a new 'class' attribute to a custom field ? - twig drupal 8
Just started to work around with Drupal 8.

I want to add class "center-block" to the field\_product\_image.

```
<img class="img-responsive {new class}"/>

```

How do i do this guys?
below is the twig code

```
   {% if content.field_product_image| render %}
    <div class="col-sm-3">
    {{ content.field_product_image }}
    </div>
    {% endif %}
    <div class="col-sm-9">
        {{ content.body }}
        {{ content.field_features }}
    </div>

```

# Answer
You can check Extra Image Field Classes module.

This module will help in adding custom classes to image field.

Extra Image Field Classes module will allow users to apply css class to image field.

> How to add custom classes to image field
>
> 1. Go to "Manage Display" of an entity type
> 2. Select "Extra Image Field Classes" format from Format column for image field
> 3. Click on settings wheel of the image field
> 4. Enter css classes in Image Class textfield
> 5. Click "Update" button
> 6. Remember to click "Save" button after making necessary changes.

Also Go for hook\_preprocess\_field()

Adding a class to default images in Drupal 8

Add class to field in Drupal 8

adding css classes into a specific image field
> 2 votes

# Answer
Normally I would say to call `addClass()` on the `image.attributes` variable in your image Twig file, but I believe images don't have a lot of template suggestions (everything goes through `image.html.twig`) which means that your class will be added to all images. Likely not what you're looking for...

Option one, inspect the variables in `image.html.twig` and see if they give you the information you need to determine when to add the new class. If so, do it in the Twig template (`attributes.addClass('new-class')`).

Option two, implement hook\_preprocess\_image in your theme's `.theme` file. Something like this:

```
function MYTHEME_preprocess_image(&$variables) {
  if (some_way_to_figure_out_if_this_is_the_right_image) {
    $variables['attributes']['class'][] = 'new-class';
  }
}

```

Hope that helps. (Edited for better code formatting).
> 7 votes

---
Tags: theming, 8
---


# Question
Title: Which implementation is better for custom breadcrumb and why?
As per answers received here, we can implement custom breadcrumb either via `module` or via `HOOK_preprocess_breadcrumb`.

Via `module`:

In `custom_breadcrumb.module` file

```
<?php

namespace Drupal\custom_breadcrumb;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;

/**
 * Class Breadcrumbs.
 *
 * @package Drupal\custom_breadcrumb
 */
class Breadcrumbs implements BreadcrumbBuilderInterface {
  use StringTranslationTrait;

  /**
   * {@inheritDoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'entity.node.canonical' && $route_match->getParameter('node') instanceof NodeInterface;
  }

  /**
   * {@inheritDoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $node = $route_match->getParameter('node');
    $breadcrumb = new Breadcrumb();

    // By setting a "cache context" to the "url", each requested URL gets it's
    // own cache. This way a single breadcrumb isn't cached for all pages on the
    // site.
    $breadcrumb->addCacheContexts(["url"]);

    // By adding "cache tags" for this specific node, the cache is invalidated
    // when the node is edited.
    $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);

    // Add "Home" breadcrumb link.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

    // Given we have a taxonomy term reference field named "field_tags" and that
    // field has data, add that term as a breadcrumb link.
    if (!empty($node->field_tags->entity)) {
      $breadcrumb->addLink($node->field_tags->entity->toLink());
    }
    return $breadcrumb;
  }

}

```

and then in `custom_breadcrumb.services.yml`

```
services:
  custom_breadcrumb.breadcrumbs:
    class: Drupal\custom_breadcrumb\Breadcrumbs
    tags:
      - { name: breadcrumb_builder, priority: 100 }

```

Via `HOOK_preprocess_breadcrumb`, as mentioned in the answer here

Both the ways are achievable, but the question is which one should be followed and why as a **best practice**?

# Answer
> 4 votes
When you build a module which for example provides a new content or entity type you can include a breadcrumb builder, because you might have data fields that the standard breadcrumb builder doesn't know of and you want to process them in your breadcrumbs. An example for this would be `Drupal\book\BookBreadcrumbBuilder` from the core book module.

When you build a theme and want to modify the breadcrumbs already built by the installed core, contrib and custom modules you use a theme based solution in a preprocess hook.

So best practice depends on which level you are working on. Not a good idea would be in this example if the book module would use a preprocess hook.

---
Tags: 8, breadcrumbs
---


title: unable to create new site

text:
# Question
Title: unable to create new site
I am new to drupal. Trying to understand the possibilities of drupal, I have installed drupal8 and followed some tutorials to create a site with a custom theme, custom modules and custom blocks. So far so good.

Now I have this first test site working (installation in public\_html), I wanted to create a second site, served by the same installation. I want to try and make a drupal8 version of an existing site of my company.

Following more tutorials, I have tried several things, but I am unable to get it working. I did the following:

* my first site's URL is http://localhost, I tried to get the url http://localhost/owtest working
* In public\_html I have created a symlink with name owtest
* In sites/ I created a directory owtest, containing a settings.php and an empty directory files/
    + I created a database for the new site. The first site's database name was 'DRUPAL' with user 'DRUPAL', for the new site I created database 'OW' with the same user.
    + in owtest/settings.php, I changed the database name to OW
    + I ran update.php, thereby clearing the cashes.

If I now go to 'localhost/owtest', it looks the same as the 'localhost' site; if I add content to the site, the same content appears to the 'localhost' site. It seems the new site does not use the new database.

Clearly, I am missing a required step. Who can help me in getting this to work? My sites/owtest/setting.php now contains

```
$databases['default']['default'] = array (
'database' => 'OW',
'username' => 'drupal',
'password' => 'drupal',
'prefix' => '',
'host' => 'localhost',
'port' => '3306',
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
);

```

thanks for helping me, Ruud

# Answer
I managed to get it working. The missing link was the sites/sites.php file. Although I *did* provide that, it started working after I put the following in it:

```
$sites = array(
   'localhost.owtest' => 'owtest',
   'localhost' => 'default',
);

```

I can now browse to localhost/owtest and have a completely different content collection that is used by the localhost site itself. Now I am facing a style problem, I keep tring...

Ruud
> 0 votes

---
Tags: multi-sites
---


title: How to (truly) alter a URL in Drupal 8

text:
# Question
Title: How to (truly) alter a URL in Drupal 8
I'm using OutboundPathProcessorInterface. I notice a few odd things about its behavior.

1. In adding, for example, "/x" to the path, it works in some cases, like admin/structure, but not others, like admin/content or the path I'm interested in, which is defined in a view. This is despite my setting the module's weight to 999 in its install file (before installing), so presumably no other module would be altering the path downstream.
2. Where it does work, such as admin/structure, the page with the original path loads, with the original URL in the address bar, but all menu links have the altered path.
3. When I watch it in xdebug, AFTER I alter the path with the query string in $options the URL comes through the function again, with the path set to the original value.

# Answer
> 3 votes
1. The module weight won't do anything here. You set the priority in the service tag.
2. You have to look what other path processors do at which priority to find the right place for your custom code. And use an inbound path processor to remove the x you have added outbound.
3. The outbound processor is called multiple times while building a page, because you usually have more than one link on the site (and not all are visible).
4. (question in comments) You can do this, outbound transfer query parameters to the path and inbound transfer parts of the path again back to the query parameters. Internally Drupal sees only the short base path with query parameters, externally you see the full path without query parameters. An example for inbound is `PathProcessorFiles::processInbound`

---
Tags: routes
---


title: Attach or embed node add form to a view

text:
# Question
Title: Attach or embed node add form to a view
I want to attach or embed a node form to a view so that when a user submits the form, the view below the form will be updated in realtime via ajax. The form will be shown above the view. My views block name is **Statuses Stream**.

I tried formblock module and putting the form in the header section of my view using views ui, but after submit, it was redirecting to the node created page.

Then I tried Advanced Form Block module. I created a form using AFB module. It is submitting the form with ajax, but it is not updating the view in the realtime.

I have just tried the Ajax Form Entity module. It is submitting and updating via ajax, but I cannot find a way to attach a view with it. However, in its settings, I can select a view mode. I need a little more flexibility.

How to Attach or embed node form to a view so that it submits via ajax and updates the view in realtime? I am open to any solution programmatically or through a module. Better if done programmatically because it will give more flexibility.

# Answer
I'ld take it from the other side: Attach a view to a node form.

First I tried it with the built-in node form. But this turned out to be quite a hassle. Instead I built a small custom form and created new nodes programmatically. Ajax submit. View refreshed. Happy, happy.

Here comes the code for a custom module. Presuming a fresh D7 standard installation.

**Info file**

```
name = MYMODULE
description = Provides cool stuff.
core = 7.x
package = Custom
dependencies[] = views

```

**Module file**

First provide a view.

```
/**
 * Implements hook_views_api().
 */
function MYMODULE_views_api() {

  return [
    'api' => 3,
  ];
}

/**
 * Implements hook_views_default_views().
 */
function MYMODULE_views_default_views() {

  $view = new view();
  $view->name = 'nodes';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Nodes';
  $view->core = 7;
  $view->api_version = '3.0';
  $view->disabled = FALSE;

  /* Display: Master */
  $handler = $view->new_display('default', 'Master', 'default');
  $handler->display->display_options['title'] = 'Nodes';
  $handler->display->display_options['use_more_always'] = FALSE;
  $handler->display->display_options['access']['type'] = 'none';
  $handler->display->display_options['cache']['type'] = 'none';
  $handler->display->display_options['query']['type'] = 'views_query';
  $handler->display->display_options['exposed_form']['type'] = 'basic';
  $handler->display->display_options['pager']['type'] = 'none';
  $handler->display->display_options['pager']['options']['offset'] = '0';
  $handler->display->display_options['style_plugin'] = 'default';
  $handler->display->display_options['row_plugin'] = 'fields';
  /* Field: Content: Title */
  $handler->display->display_options['fields']['title']['id'] = 'title';
  $handler->display->display_options['fields']['title']['table'] = 'node';
  $handler->display->display_options['fields']['title']['field'] = 'title';
  $handler->display->display_options['fields']['title']['label'] = '';
  $handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
  $handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
  /* Sort criterion: Content: Post date */
  $handler->display->display_options['sorts']['created']['id'] = 'created';
  $handler->display->display_options['sorts']['created']['table'] = 'node';
  $handler->display->display_options['sorts']['created']['field'] = 'created';
  $handler->display->display_options['sorts']['created']['order'] = 'DESC';

  /* Display: Block */
  $handler = $view->new_display('block', 'Block', 'block');

  $views[$view->name] = $view;
  return $views;
}

```

Then do the form.

```
/**
 * Provide a form.
 */
function MYMODULE_form($form, &$form_state) {

  $form['wrapper'] = [
    '#type'       => 'container',
    '#attributes' => [
      'id' => 'mywrapper',
    ],
  ];

  $form['wrapper']['node_form'] = [
    '#type'  => 'fieldset',
    '#title' => t('Add article'),
  ];

  $form['wrapper']['node_form']['node_title'] = [
    '#type'     => 'textfield',
    '#title'    => t('Article title'),
    '#required' => TRUE,
  ];

  $form['wrapper']['submit'] = [
    '#type'   => 'submit',
    '#value'  => t('Save'),
    '#submit' => ['MYMODULE_form_submit'],
    '#ajax'   => [
      'callback' => 'MYMODULE_MYCALLBACK',
      'wrapper'  => 'mywrapper',
    ],
  ];

  $form['wrapper']['view_display'] = [
    // view machine name && display/block name
    '#markup' => views_embed_view('nodes', 'block'),
  ];

  return $form;
}

/**
 * Do some validation.
 */
function MYMODULE_form_validate($form, &$form_state) {
  // Better do some validation.
  // Here or via #element_validate.
  // @see https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#element_validate
}

/**
 * Form submit. Node creation.
 */
function MYMODULE_form_submit($form, &$form_state) {

  global $user;
  $node = new stdClass();

  $node->type     = 'article';
  $node->title    = $form_state['values']['node_title'];
  $node->language = LANGUAGE_NONE;
  $node->uid      = $user->uid;

  node_object_prepare($node);
  node_save($node);

  // Empty out title field on rebuild.
  $form_state['input']['node_title'] = '';

  // Rebuild form.
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback to return the whole wrapper.
 */
function MYMODULE_MYCALLBACK($form, &$form_state) {

  return $form['wrapper'];
}

```

I've put it on a sample page to see it in action.

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items['example/form'] = [
    'title'            => 'Example Form',
    'description'      => 'A form to mess around with.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['MYMODULE_form'],
    'access arguments' => ['create article content'],
  ];

  return $items;
}

```
> 2 votes

---
Tags: 7, views, forms, blocks, ajax
---


# Question
Title: Ajax callback of select form field not triggered when changed by javascript, only when changed manually
I have a simple ajax form with select form input:

```
$form['children']['number_children'] = array(
  '#title' => t('Počet detí'),
  '#type' => 'select',
  '#options' => range(0, 15),
  '#default_value' => $number_children,
  '#ajax' => array(
    'callback' => 'ajax_callback_registration_children',
    'wrapper' => 'children-div',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

```

When the select input is changed manually it properly executes an ajax and appends new inputs into the form. But I need to trigger the ajax callback by javasrcipt code that is changing the selected option:

```
$('#children-div select[name="number_children"]').val('3').change();

```

This changes the value, but the ajax is not triggered at all. Why is it not working and is there something I could do?

---

**EDIT**: It works when this command: `$('#children-div select[name="number_children"]').val('3').change();` or another way of triggering an event is typed in browser console, but not if the same code is executed from my chrome extension. Is it possible that Drupal somehow verifies what exactly triggered the event?

# Answer
> 1 votes
try to specify the event, like

```
$form['children']['number_children'] = array(
  '#title' => t('Počet detí'),
  '#type' => 'select',
  '#options' => range(0, 15),
  '#default_value' => $number_children,
  '#ajax' => array(
    'callback' => 'ajax_callback_registration_children',
    'wrapper' => 'children-div',
    'method' => 'replace',
    'effect' => 'fade',
    'event' => 'change',
  ),
);

```

this should be sufficent .. (but select uses change already as default event ..)

**other things to try could be**

add a custom event, like:

```
'event' => 'custom_change',

jQuery('select').trigger('custom_change');

```

See How to trigger Ajax forms machinery

or invoke the callback yourself:

```
Drupal.ajax['#ID'].eventResponse('#ID');

```

# Answer
> 1 votes
I had a similar problem when I tried to trigger a click on a form button to fire an Ajax submit in Drupal. It then turned out it explicitly needed to be a `.mousedown()`. Nothing else.

See this question here for reference: How to programmatically trigger a click on an AJAX enabled form submit button?.

So, I guess that all that's not sufficiently here is you calling `.change()`. Please try all other alternative possibilities.

In views-admin.js file of the Views module I found `.trigger('change')` for overriding a select. Maybe that's it.

# Answer
> 0 votes
Try this code

Ajax callback function :

```
/**
 * Ajax Callback
 *
 * @param type $form
 * @param type $form_state
 * @return type
 */
function ajax_callback_registration_children(&$form, $form_state) {
  $commands = [];

  $commands[] = ajax_command_html('#children-div');
  // Call js.
  $commands[] = ['command' => 'afterAjaxCallbackExample',
    'selectedValue' => $form_state['values']['number_children'],
  ];
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

js:

```
(function($, Drupal){
// Our function name is prototyped as part of the Drupal.ajax namespace, adding to the commands:
Drupal.ajax.prototype.commands.afterAjaxCallbackExample = function(ajax, response, status)
{
   // your code here..
};

```

}(jQuery, Drupal));

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


# Question
Title: How to redirect the user to a product page (node) after payment is made?
How to redirect the user to a product page (node) after payment is made?

I'm using the Commerce Express Checkout module. That's why in the Shopping cart can be just one product.

# Answer
One option is to use hook\_menu\_alter in a custom module to override your current destination page with a redirect.

```
<?php

function mymodule_menu_alter(&$items) {

    $items['current/checkout/path'] = array(
        'page callback' => 'drupal_goto',
        'page arguments' => array('new/checkout/path'),
        'access callback' => TRUE,
      );

}

```

# Update:

To use the above code, you'll have to create a module.

1) Create a directory to be used for this module, e.g. `/sites/all/modules/MYMODULE`

2) Create MYMODULE.info, e.g. `/sites/all/modules/MYMODULE/MYMODULE.info`. Paste the following into the file.

```
name = MYMODULE
description = "Module description."
package = Custom
core = 7.x

```

3) Create MYMODULE.module, e.g. `/sites/all/modules/MYMODULE/MYMODULE.module`. Paste the following into the file.

```
<?php

function MYMODULE_menu_alter(&$items) {

    $items['current/checkout/path'] = array(
        'page callback' => 'drupal_goto',
        'page arguments' => array('node/123'),
        'access callback' => TRUE,
      );

}

```

4) Replace all instances of `MYMODULE` with your desired module name. Replace `current/checkout/path` with the current path of the checkout. Replace `node/123` with the new checkout path. Lastly, enable your new module.

This will tell Drupal to replace the current checkout page with a redirection to the new one.
> 0 votes

# Answer
Another option is to add a rule, based on the event 'checkout complete' / 'first paid in full'.
> 0 votes

---
Tags: redirection, commerce
---


# Question
Title: Commerce PayPal wps sends to and gets data from sandbox but no payment method available
I'm on localhost without ssl and fix IP. I can checkout with PayPal WPS, go to sandbox, confirm as buyer, and when I click in the sandbox I go back to my testsite after confirming to leave SSL.

In my logs I can see (watchdog) that the function commerce\_paypal\_wps\_redirect\_form\_validate() works fine and gives me a lot of data from my client and the transaction.

In my sandbox seller account I can see the payment is accepted and I earned my bucks ;)

Here the problems:

The orders overview at admin/commerce/orders only shows pending orders instead completed although the posted data from paypal show

> \[payment\_status\] =\> Completed

Next when I go to the payment of any order I see that there's no payment method available although payment is done per WPS.

admin/commerce/orders/1/payment:

> No payment methods available to add payments.

I believe that these are the reasons why my hook I want to use is not called?? I want to change the user role after the transaction is completed so I took hook\_commerce\_paypal\_ipn\_process() without success.

Does anybody has any ideas??

My modules: commerce 7.x-1.11+52-dev, PayPal 7.x-2.3+4-dev, Commerce (Tax)7.x-1.0-rc2, rules 7.x-2.9

# Answer
> 0 votes
PayPal WPS has to send IPN to your Drupal website(application) in order for Drupal to process and store payment for the order. When IPN is received and payment transaction is registered in db you can then run some logic (via Rules) to set the order status accordingly and do other things.

You are not receiving IPN from PayPal because your website is on the local host. You have to host your website on live domain(sub domain, domain sub folder , etc.) so that PayPal server can ping yours and send you data.

Read your question a few more times, and here's more thoughts:

You may be messing up PayPal WPS module's logic by using that hook in a wrong way. Why not assign the role via Rules?

# Answer
> 0 votes
Looking at this problem today (paypal POST shows 'complete', but orders do not), I approached it like this:

* Checking the orders' 'Revisions', it became clear that some (default) rule triggered and *returned* the order from 'checkout: complete' to 'pending'. Based on the event 'checkout complete'. I disabled that rule.
* I use a new rule based on the event 'first paid in full' to 'complete' orders automatically. (plus do specific workflow reactions there)

The availability of payment methods to different users was, as well, dependent on rule conditions, per each specific payment method.

---
Tags: commerce, payment-gateways
---


title: How to translate a warning message?

text:
# Question
Title: How to translate a warning message?
There is a code `define('SPAMBOT_DEFAULT_BLOCKED_MESSAGE', 'Your email address or username or IP address is blacklisted.');` How to make the phrase 'Your email address or username or IP address is blacklisted.' translatable? (with t).

# Answer
Depending on how often it appears, you can call `t(SPAMBOT_DEFAULT_BLOCKED_MESSAGE)` every time you invoke the constant in your code. For instance:

```
<?php

define('SPAMBOT_DEFAULT_BLOCKED_MESSAGE', 'Your email address or username or IP address is blacklisted.');

/**
 * implement hook_page_alter()
 * JUST AN EXAMPLE. REPLACE WITH YOUR OWN HOOK OR FUNCTION
 */
function mymodule_page_alter(&$page) {
  drupal_set_message(t(SPAMBOT_DEFAULT_BLOCKED_MESSAGE));
}

```

In order to be able to see the string in the "Translate interface" page (`admin/config/regional/translate/translate`), you need to display it at least once in a language different from the default language of your site.
> 0 votes

---
Tags: i18n-l10n
---


title: Inline entity form ajax

text:
# Question
Title: Inline entity form ajax
I am trying to update some field options in an inline entity form with ajax. This should happen, when someone selects a value in an other field.

I already have some code which "works", but the problem is that you can edit multiple items and there seems to be a problem with the wrapper\_id, because it is for all items the same and the *entityForm* function is called multiple times.

So what is the best way to do this?

# Answer
> 0 votes
What about adding wrappers to the fields?

In your hook\_form\_alter:

```
$form['field_name']['#prefix'] = '<div class="last">';
$form['field_name']['#suffix'] = '</div><div class="clearfix"></div>';

```

Check https://www.webomelette.com/drupal-form-api-prefix-suffix

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


# Question
Title: When while saving nodes do I have old and new vid available at once?
I'ld like to programmatically trigger some very basic email notification when a new revision of a node is being created. I want to send a link to the compare page `/node/$nid/revisions/view/$old_vid/$new_vid`.

But I wonder on which hook when saving a node do I have the old and the new vid available at once? `hook_node_presave()` looks like a dead end to me.

---

This question is not specifically about D7. Though it's D7 I'm using right now, I'ld prefer to find a solution for both D7 and D8.

# Answer
You simply can add a custom submit callback to the node form.

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  $node_forms = [
    'article_node_form',
  ];

  if (in_array($form_id, $node_forms)) {

    // Add a custom submit callback.
    $form['actions']['submit']['#submit'][] = '_MYMODULE_postsave';
  }
}

```

There you can access the original vid from the `$form_state` array. And when you load the freshly saved node you'll have the new vid available.

```
/**
 * Custom submit callback.
 */
function _MYMODULE_postsave($form, &$form_state) {

  $old_vid = $form_state['values']['vid'];
  $nid = $form_state['values']['nid'];
  $node = node_load($nid);
  $new_vid = $node->vid;

  // Voilà!
  dpm($old_vid, 'OLD_VID');
  dpm($new_vid, 'NEW_VID');

  // Do your stuff here
}

```

For reference: https://drupal.stackexchange.com/a/221041/15055
> 0 votes

---
Tags: nodes
---


# Question
Title: Form submit results in "Too many redirects" error for anonymous users
I have a custom route on my site at `/search`. This page has a couple of forms on it (defined with FormBase).

When I am logged in, the form appears to work.

When I am anonymous, many many requests occur when I submit and causes a "too many redirects" error in the browser.

Here is my routing.yml

```
mymodule.search:
 path: '/search'
 defaults:
   _title_callback: 'Drupal\mymodule\Controller\SearchPage::title'
   _controller: 'Drupal\mymodule\Controller\SearchPage::build'
 requirements:
   _permission: 'access content'

```

Here is one of the forms:

```
<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Component\Utility\Xss;
use Drupal\Component\Utility\Unicode;

/**
 * Class KeywordForm.
 *
 * @package Drupal\mymodule\Form
 */
class KeywordForm extends FormBase {

  /**
   * Symfony\Component\HttpFoundation\RequestStack definition.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructor for our class.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'iana_keyword_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $keywords = Xss::filter($this->requestStack->getCurrentRequest()->get('keywords'));
    $site_ids = $this->requestStack->getCurrentRequest()->get('site_id');
    $sort_by = $this->requestStack->getCurrentRequest()->get('sort_by');
    $sort_order = $this->requestStack->getCurrentRequest()->get('sort_order');

    $form['#attributes']['class'][] = 'search-result__form';

    if (!is_array($site_ids)) {
      $site_ids = [];
    }

    $form['keywords'] = [
      '#type' => 'textfield',
      '#cache' => ['contexts' => ['url.query_args:keywords']],
      '#default_value' => Unicode::strlen($keywords) ? $keywords : '',
      '#prefix' => '<div class="search-box__input js-search-input">',
      '#suffix' => '</div>',
      '#attributes' => [
        'placeholder' => Unicode::strlen($keywords) ? $keywords : t('Search for...'),
      ],
    ];

    $form['site_id'] = [
      '#type' => 'hidden',
      '#value' => $site_ids,
    ];

    $form['sort_by'] = [
      '#type' => 'hidden',
      '#value' => $sort_by,
    ];

    $form['sort_order'] = [
      '#type' => 'hidden',
      '#value' => $sort_order,
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      '#attributes' => [
        'class' => [
          'search-box__button',
        ],
        'data-twig-suggestion' => 'search_results_submit',
      ],
    ];

    $form['#cache']['contexts'][] = 'session';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect(
      'mymodule.search',
      [
        'keywords' => $form_state->getValue('keywords'),
        'site_id' => $form_state->getValue('site_id'),
        'sort_by' => $form_state->getValue('sort_by'),
        'sort_order' => $form_state->getValue('sort_order'),
      ],
      [
        'query' => [
          'keywords' => $form_state->getValue('keywords'),
          'site_id' => $form_state->getValue('site_id'),
          'sort_by' => $form_state->getValue('sort_by'),
          'sort_order' => $form_state->getValue('sort_order'),
        ],
      ]
    );
  }

}

```

It looks like at some point, I hit this bit of code in the FormBuilder class:

```
// If the form returns a response, skip subsequent page construction by
// throwing an exception.
// @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber
//
// @todo Exceptions should not be used for code flow control. However, the
//   Form API does not integrate with the HTTP Kernel based architecture of
//   Drupal 8. In order to resolve this issue properly it is necessary to
//   completely separate form submission from rendering.
//   @see https://www.drupal.org/node/2367555
if ($response instanceof Response) {
  throw new EnforcedResponseException($response);
}

```

Here is what Google Chrome devtools window shows for network activity:

What is going on here, and how can I fix this? I need the values attached to the URL when the form is submitted.

All of the Forms are displayed on the sidebar and header as blocks injecting those forms. Only 3 forms exist, keyword and a simple checkbox filter.

For the life of me, I can't see what is wrong.

The cache\_render table is filling up with various search URLs, it should not, though no matter what I set #cache to, it does.

# Answer
Thanks to 4k4 and some folks in IRC, it turns out that the culprit here is the Redirect module.

I was able to solve this by:

* Disable `Enforce clean and canonical URLs.` in Redirect
* Add `/search` and `/search*` to URLs to ignore in Redirect

After setting that and clearing cache, anonymous users were no longer stuck in an endless redirect loop when using search forms.
> 2 votes

---
Tags: 8, forms, routes
---


title: Is relationships scalable?

text:
# Question
Title: Is relationships scalable?
I have a Drupal 8 site using the OpenSocial profile. It's a social profile and users can follow other users. This is implemented using the Flags module.

In the site, I created a view for users to see contents of the users they are following and it uses a relationship to user entity, and lists the content of user flagged by the current users.

As the site the content differs for each users, it can't be cached. What will be the best way to scale in this case? Is there a different method to follow other than a relationship?

Is there a way we can use a search\_api based index view for this purpose?

# Answer
> 2 votes
> As the site the content differs for each users, it can't be cached.

Well, that is not entirely true. At least for Drupal 8 the options for caching have improved drastically. Previously we could cache a query and its output, but Drupal 8 comes with tag-based caching.

Every entity in the system can (and core entities by default) expose a cache tag. This allows individual entities to be cached. Views tag-based caching in turn uses these tags to determine if the cached view output can be served or should be rebuilt.

This means that the view query will still be executed, but all the individual nodes can be served from their individual caches. If none of the nodes has been updated, the rendered output of the view will be served from cache too.

As for scalability (SQL vs NoSQL is not really a Drupal question), there is a tradeoff (but I really do not know enough of this to provide a good explanation). A views relationship is nothing more than an SQL join, this means that all data exists once and is merged into a data set on request. If you do not want to use relationships but a search\_api based approach, the same data set should be composed elsewhere. Since you do not want to use relations you should fetch all nodes of all followed users in one run.

Depending on how your view and search database are configured, this could result in every node getting stored once in the dataset of every follower. With a lot of users and a lot of content this can grow in size very fast. It will likely be faster though because you'll only have to lookup one id instead of all the id's of the entities on the joined tables.

TL;DR It depends on what you show and how you build the index.

# Answer
> 0 votes
Yes i believe you can go ahead with scaling it via search api. And if you have lot of content on your website. You can go for implementing Elastic search. It works much better than Apache Solr.

I think Elastic search does not have Drupal 8 module. But you can always contribute to d.org. (If you have enough timeline.)

---
Tags: 8, search, views
---


# Question
Title: How to disable CACHE in FORM which loads database values in form fields
I am loading database values in my FORM and seems form is CACHING and loading old data from the database.

I have followed instruction here (How do I prevent a form from being cached for Anonymous users in D8?) but still old data is loaded in form fields.

Here is my code and would appreciate if anyone can shed light where I am missing;

....

```
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {

// Define form fields.
$form['#cache']['max-age'] = 0;

$form['name'] = array(
  '#type' => 'textfield',
  '#size' => 80,
  '#title' => t('Your Name'),
  '#default_value' => $result->name,
);

return $form;
}

```

....

Do I have to add 'use Drupal\Core\Cache;' on top of this file?

Thanks a lot.

# Answer
In the linked question the module *Internal Page Cache* was not enabled. If you don't want to disable page caching for all pages, but only for this form page, then add `\Drupal::service('page_cache_kill_switch')->trigger()` before you return the form:

```
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {

// Define form fields.
$form['#cache']['max-age'] = 0;

$form['name'] = array(
  '#type' => 'textfield',
  '#size' => 80,
  '#title' => t('Your Name'),
  '#default_value' => $result->name,
);

\Drupal::service('page_cache_kill_switch')->trigger();

return $form;
}

```
> 4 votes

---
Tags: forms, database, caching
---


# Question
Title: add "items_per_page" number in title tag and meta tag
I created a view which has set up "Exposed items per page options." I used "24,48,72" as my options. Here is my view "Exposed setting": When I choose "items per page" as 72, the url of that page will change to "https://www.domain.com?items\_per\_page=72". Here is a test page screenshot:

My question is how can I add the number to "title" tag in order to distinguish "title" for SEO. There are some websites suggest to used `[current-page:page-number]` token, but this is not working in my case. Does anyone have any idea?

# Answer
I got a solution. Just add the following code in template.php file.

```
function yourtheme_preprocess_html(&$vars){
    // add pager number to title.
    parse_str($_SERVER['QUERY_STRING']);
    if(isset($items_per_page)){
        $vars['head_title'] .= $items_per_page;
    }
}

```
> 0 votes

---
Tags: 7, views, meta-tags
---


title: Hook module placement

text:
# Question
Title: Hook module placement
I have the following file named background\_image\_style.module

In my Drupal 8.3.3 site, paragraphs.module is at MySite/web/modules/contrib/paragraphs/paragraphs.module.

I installed the site and all contributed modules with Composer.

```
composer require drupal/paragraphs
vendor\bin\drupal module:install paragraphs

```

Where does my hook module go? (I just copied it in where the paragraphs.module is.) Are there any other overhead steps that needs to be done (e.g. editing other files)?

I tried several locations and cleared the cache each time.

```
    /**
     * Implements paragraphs().
     */
    function background_image_style_preprocess_paragraph__banner(&$variables) {
      $paragraph = $variables['paragraph'];
      if (!$paragraph->field_image->isEmpty()) {
        $image = $paragraph->field_image->entity->url();
        $variables['attributes']['style'][] = 'background-image: url("' .                 $image. '");';
        $variables['attributes']['style'][] = 'background-size: cover;';
        $variables['attributes']['style'][] = 'background-position: center         center;';
      }

```

# Answer
> 1 votes
From Where to Put the Module Files:

> **Manual import location**
>
> If you import a module 'manually', you should place your module in that same default recommended location, *HERE*:
>
> \[d8-root\]/modules/*HERE*
>
> \[Themes: \[d8-root\]/themes/*HERE*\]

It's a good idea to keep custom and contrib modules separate, hence Drupal Project putting contributed modules into their own folder; following on from that, there's a pretty common convention to place custom modules under \[d8-root\]/modules/custom/. But you don't have to, you can use whatever hierarchy you like under /modules, Drupal will pick up anything it finds recursively.

After it's in place, don't forget to *enable* the module, or it won't do anything.

# Answer
> 0 votes
This preprocess hook can go right in the `themename.theme` file. In the theme, the name of the hook needs to be `themename_preprocess_paragraph__banner` (where `themename` is the name of your active theme).

Otherwise it would have to go in a custom module, and the hook name would be the module name instead of the theme name.

# Answer
> -1 votes
The problem was the .yml file missing. A little different from d7 but more or less the same concept.

---
Tags: hooks
---


title: Security update for patched module

text:
# Question
Title: Security update for patched module
Is it necessary to re-patch an existing patched module when doing a security update for that module? I am not interested in keeping it patched. Or will this potentially break something?

# Answer
Most likely you will need to repatch the module, if you doing it manually.

If are using composer to manage your drupal set up, you can use "cweagans/composer-patches", and this composer plugin it will reapply the patch for you automatically and let you know if the patch will no longer work on the newer version of the module.

This is a big time saver.
> 1 votes

---
Tags: 8
---


# Question
Title: Populate questions and answers (Display two types of content two different ways on one page intermittently)
I am using the Answers module and would like the landing page to display all questions as well as all answers, as they are posted, and each would render different fields e.g. I want the questions and answers to look differently but still show up in the same feed. Currently, it uses a view to list all the questions only. Is this possible?

For an example of what I mean, this is a screenshot Quora.

>

I read this answer but do not want to use panels, but am also not sure if this solution will render questions and answers differently from each other in the list.

Please notice that the answer shown in this example isn't related to the question; it's just a random answer to a question. That's what I'm looking for.

# Answer
It's likely not possible to do what I wanted to do, having completely different fields for different content types within one view (as fields, not teasers or entities). I was able to incorporate some of the suggestions by the others who have answered but changed my fields so that they could apply to both content types.

I changed the view to show both questions and answers. I made the number of answers field not show unless there is an answer (so that it doesn't show "Answers:0" in the answers and then I renamed the content types to "Answered" and "Question asked" so that the content shows which one it is. Also, the question title wasn't showing up so I had to read the title field for answers. All is well so far.
> 0 votes

# Answer
You also get a **"Answers to a Question"** view with this module. Change display format to "Fields" and create a block pulling all the fields you need. You might as well find Relevant Answer (extends Answers) helpful found here.

> The module provides two predefined blocks to display questions and their corresponding answers: 'Popular Questions' and 'Recent Questions'.

**Edit:** Import this view- you should get a "Q & A feed" block which populates questions and its answers, apply a sort criteria to meet your need.

```
$view = new view();
$view->name = 'q_a_feed';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Q & A Feed';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Q & A Feed';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Answer to the question */
$handler->display->display_options['fields']['field_answer_question']['id'] = 'field_answer_question';
$handler->display->display_options['fields']['field_answer_question']['table'] = 'field_data_field_answer_question';
$handler->display->display_options['fields']['field_answer_question']['field'] = 'field_answer_question';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'answer' => 'answer',
  'question' => 'question',
);

/* Display: Q & A feed */
$handler = $view->new_display('block', 'Q & A feed', 'block');

```
> 0 votes

# Answer
In views, under Advanced, add Relationship `Content: Answer to the question`

Then in Fields add `Content: Answer to the question (Answer to the question)`
> 0 votes

---
Tags: views, 7
---


title: Multi vendor products, single store?

text:
# Question
Title: Multi vendor products, single store?
How can I create products in Drupal8 eCommerce, which are from different vendors, but I'm handling it trough a single store ? (Vendors should be invisible to the end customer).

I want in addition to keep track internally (for my own accounting purposes) which item from which vendor was sold, so I can reimburse the specific vendor. Is there a way to put/attach "out-of-bound" info to products and eventually orders ?

I'm still in research phase, experimenting with Drupal. Is such thing possible ?

# Answer
> 1 votes
Yes it is. In the end even unlimited with custom code ..

To easily limit the access for a vendor to only his products, each one would need one or more product types, then you can apply the right permissions. Also I would add the vendor/user as a reference (field) to that product type.

There very good shipping methods, applicable for different countries etc.

---
Tags: commerce
---


# Question
Title: Content type permission to specific users
How do I set content permission so that specific content types become visible/usable to the admin user only, while other content types may be visible by other user roles?

After I added new content types, I checked the rebuild permissions.

Content access is working fine but the problem seems to be the fact that the enw content types aren't made visible / accessible to the other roles...

# Answer
The core's built-in support for node access control is rather course, and to control a specific role's access to *view* a page, it is *not* enough to go to `admin/people/permissions` to set permissions, since there is only a global setting for "*View published content*" that apply to *all* published content.

However. to give the permission to *Create* new content (*node/add*), there is no need for an extra module, since all other permissions, i.e. *Create, Edit, Delete*, is managed by the Drupal core and there are per-role settings in the built-in permissions interface. First, just to make sure content is visible, navigate to `admin/people/permissions` and make sure you have the permission *View published content* checked for the authenticated user role.

Then, just below it, locate the check boxes to "Create new content" for the content types you want users beyond the administrators to be able to create, and check those for the roles you want to have this permission granted (ditto with the *Edit* and *Delete* permissions).

Also make sure new content is *Published*. If content is not Published, the only user that has access to it us the super admin user.

To set the default to Published for a new content type, navigate to *Administration → Structure → Content types*. Then click on the edit link for the type you want to configure- Locate the "Publishing option" tab. and make sure that there is a tick mark for "Published" under "Default options".

If you need fine grained access control *beyond this*, you need to install a node access control module.

The module I recommend for this is Content Access. It let you control access per content type and user role.

To set the per content access settings, navigate to *Administration → Structure → Content types*. Then click on the edit link for the type you want to manage, and then on the Access control tab. This takes you to the control panel for role based access control settings. The screen dump below shown how do set this for the built-in content type "Basic page":

After setting the permissions the way you want, click "Submit".

There is a nice tutorial about installing and configuring the Content Access module on YouTube. (Thanks to @shrish for bringing this to my attention.)
> 4 votes

# Answer
Content access is no longer under active development (according to the project page on drupal.org). It's a good module but for long-term site sustainability, it might not be the best solution.

Another option is the field permissions module (https://drupal.org/project/field\_permissions). It offers more granular control over the fields of each content type (which is more than what it sounds like you need) but it can easily be used to accomplish your objective.

I've used the field permissions module on a number of sites with great success. It's stable and very easy to use. I can offer some tips if you decide to use field permissions.

Here's a snipit from the module's README.txt file:

# INSTALLATION

1) Copy all contents of this package to your modules directory preserving subdirectory structure.

2) Go to Administer -\> Modules to install module. If the (Drupal core) Field UI module is not enabled, do so.

3) Review the settings of your fields. You will find a new option labelled "Field visibility and permissions" that allows you to control access to the field.

4) If you chose the setting labelled "Custom permissions", you will be able to set this field's permissions for any role on your site directly from the field edit form, or later on by going to the Administer -\> People -\> Permissions page.

5) Get an overview of the Field Permissions at: Administer -\> Reports -\> Field list -\> Permissions
> 2 votes

# Answer
Related, I've found the use of an added extra content type, ie "Draft Document" or "Draft Data" etc for admin/exec/dev user permissions only, along with the Node Convert module, allows publishing of nodes in the "site flow and layout" as published rather than unpublished first revisions of Page, Article entities etc. This tweak seems a need to compensate for the D7 ui workflow weakness of layout/design/workflow/permissions of core and core node. Node Convert Node does A1 job of field mapping so its practical even for a newbie, but caveat, Node Convert may not play nice with VBO (maybe).

If a previlaged user wants to make a doc, simple data or image page node and see how it looks on a D7 site screen/layout/display before revealing it to the world on a live site (rather than a hidden/dev/beta site), unfortunately D7 core does not provide rendered layout of the standard UNPUBLISHED nodes, even if you are the admin/exec/dev and superuser 1. NODES NEED TO BE PUBLISHED TO BE DISPLAY unless templates and API preproccessing for rendering by programmers is done or ACL or field permissions are used one way or another. One of the Drupal glitches to my mind.

Therefore it's unfortunate ACL - Access Control module (that i believe funny enough mirrors older D6 content type node permissions options/config and as well, an ADCI Solutions (see drupal association) module for this)... is not a most popular, or secure solution to this subtle but substantial fail in Drupal realm. Guess it's time i dig into D8.

Of course, maybe the Workflow module and rules and/or triggers is another way, more sophisticated way, to solve like challenges
> 0 votes

---
Tags: nodes
---


title: How to quickly tell what a URL maps to?

text:
# Question
Title: How to quickly tell what a URL maps to?
I'm in a new position working on an existing Drupal 7 site that I didn't help build. None of the original devs are here. Amongst other modules, the site makes uses of panels, panelizer, aliases, and redirects.

I get requests from marketing to update or change a page, and they include a URL. The URL is often an alias, but sometimes it can be a panels page, or a drupal entity "overriden" by panelizer.

Is there an easy way to see what exactly a URL maps to when I get a URL from marketing?

# Answer
> 0 votes
There is no easy way. You have to have deep knowledge of the site's content to know how to edit what appears on the page. This is only obtained through poking around the site or asking a knowledgeable colleague.

---
Tags: 7, uri
---


title: How can I get the complete query?

text:
# Question
Title: How can I get the complete query?
I am displaying a Drupal 8 view. I see that all of the fields that are displayed in the view are not in the query.

How does this work?

# Answer
For query tracing you can use devel module. Devel module include the Web Profiler module which shows many options. Even you can see the all queries executed for page.

Following are the sample details of web profiler.

UPDATE: So how you can see your view query in web profiler? Well, follow this steps.

1. For tracing purpose disable view cache. "Select 'No Cache' from advance section".
2. Then Clear all drupal cache.
3. Open views output page.
4. Click on database link from web profiler.
5. Now search in page(Ctr+F) your field name. E.g: Here I added one field in my view, that is field\_image. So I search that and I get view query..
6. Once you found out your query, you will see there is no parameter in query, Well to see which paraters query is taking click on "Info" tab of query. And you will see all parameters of placeholder.
> 3 votes

---
Tags: views
---


# Question
Title: Rendering a form using \Drupal::service('entity.form_builder')->getForm($entity, 'default') is returning a plain form, before hook_form_alter
I'm rendering a form programmatically. The following code works:

```
$addressForm = \Drupal::entityTypeManager()
  ->getStorage('profile')
  ->create(array('type' => 'customer', 'uid' => $uid));
$finalform =  $this->entityFormBuilder()->getForm($addressForm);

```

However, it is rendering the form before `hook_form_alter()` has been called.

For example, in `hook_form_alter()` we added a `#after_build` callback method and custom validations, but the changes made in these functions are not reflected in `$finalform`.

How do I ensure `hook_form_alter()` changes are made to the rendered output?

**.module file**

```
function custom_profile_form_profile_customer_add_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $form['formtitle'] =  array(
    '#type' => 'markup',
    '#weight' => -100,
    '#markup' => '<h2>Old Address Form</h2>',
  );
  /* ....
.... */
}

function custom_profile_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_FORM_ID_alter') {
    $group = $implementations['custom_profile'];
    unset($implementations['custom_profile']);
    $implementations['custom_profile'] = $group;
  }
}

```

**.routing.yml**

I have created a new route for the Address page in /modules/custom/custom\_profile/custom\_profile.routing.yml,

```
commerce_add_address.get:
  path: '/checkout/{uid}/customer/add'
  defaults:
    _controller: '\Drupal\custom_profile\Controller\newAddressBook::commerce_add_address'
  options:
    parameters:
      uid:
        type: integer
  methods:  [GET,POST]
  requirements:
    _permission: 'access content'

```

**Controller**

in src/Controller/newAddressBook.php file

```
public function commerce_add_address($uid) {
  //To get profile Add Address form
  $addressForm = \Drupal::entityTypeManager()
      ->getStorage('profile')
      ->create(array(
        'type' => 'customer',
        'uid'  => $uid
      ));

  $finalform = $this->entityFormBuilder()->getForm($addressForm);
  $build['#theme'] = 'usernewaddress';
  $build['#data'] = array();
  $build['#data']['form'] = $finalform;

  return $build;

```

# Answer
Ensure that your implementation of `hook_form_alter()` runs at the right time via `hook_module_implements_alter()`.

> This hook is invoked during `\Drupal::moduleHandler()->getImplementations()`. A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

But pay attention when using possible variations of `hook_form_alter()`.

> Note that hooks invoked using `\Drupal::moduleHandler->alter()` can have multiple variations(such as `hook_form_alter()` and `hook_form_FORM_ID_alter()`). `\Drupal::moduleHandler->alter()` will call all such variants defined by a single module in turn. For the purposes of `hook_module_implements_alter()`, these variants are treated as a single hook. Thus, to ensure that your implementation of `hook_form_FORM_ID_alter()` is called at the right time, you will have to change the order of `hook_form_alter()` implementation in `hook_module_implements_alter()`.

See? Right now you are checking for `if ($hook == 'form_FORM_ID_alter')` which won't work. Fix it by replacing it with `if ($hook == 'form_alter')`.

---

If that doesn't work try to change your module's weight via `module_set_weight()`.
> 2 votes

---
Tags: 8, forms
---