# Question
Title: How can I display a login and registration form, with an extra field on registration, and hybridauth in a modal?
I need to display a modal login and registration form if a user accesses a particular page.

On the registration form, I need to collect a phone number.

I need to show the hybridauth login on the form as well. Is there a solution, or compatible modules to make this solution?

It's a common login/registration solution, so I'd think Drupal has this already.

# Answer
> 1 votes
Yes, this has a common solution with preexisting modules. Here's the summary with your 3 requirements:

* **Forcing capture of telephone on registration:**
* **Hybridauth Social Login:**
    + After enabling the module, and installing the libraries to the sites/all/libraries directory, configure each social network and set your other login options accordingly.
* **Modal Popup:**
    + The Modal Forms module enables popup modals for the both the **user/login** & **user/register** paths. The popup presents the same login form as you see in Drupal so it will contain the HybridAuth login elements as well. The module lets you configure modal popups on a per-page basis so you can choose the pages where you want login/registration presented as modal form.

# Answer
> 0 votes
You could use webform & webform rules to create a user with more details than the standard registration page.

For HybridAuth-- would this be the module you're looking for? https://www.drupal.org/project/hybridauth

---
Tags: 7, users, chaos-tool-suite, authentication-authorization
---


title: Medium editor showing "placeholder"

text:
# Question
Title: Medium editor showing "placeholder"
I'm trying to use the Medium module, but for some reason it just shows "placeholder" when I click on the **Configuration \> Content Authoring \> Medium** Editor. Could you point me to any solution for that?

# Answer
> 1 votes
That module has not been finished, yet. The function that should return the form for the settings of that module doesn't even allow to set any settings; it just output that *Placeholder* text you see.

```
  $form = array();

  // @TODO: Allow users to choose the image style used for media embeds.
  // @TODO: Allow users to choose which media plugins should be exposed.

  $form['whatever'] = array(
    '#markup' => 'Placeholder'
  );

  return $form;

```

The module is in a alpha state; don't consider it ready for production.

---
Tags: 7
---


# Question
Title: Webform A partially-completed form was found. Please complete the remaining portions
I'm seeing this message on my webforms:

> A partially-completed form was found. Please complete the remaining portions

How can I suppress this message for Webform version 7.x-4.10?

# Answer
This is shown if you have the **Show "Save draft" button** option ticked in any webform and is hardcoded into the Webform form builder. If you want to override the message display the Disable Message module can help you here.

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.
> 0 votes

---
Tags: webforms, status-messages
---


title: how to make url string absolute?

text:
# Question
Title: how to make url string absolute?
In order to get entity link, I'm using:

```
$entity->getTranslation($language)->url();

```

So it gives me : /en/node/21

But I want this url to be absolute.

How to pass `$options = array('absolute' => TRUE);` in above node url?

# Answer
> 8 votes
The options are the second parameter in `url()`, then you also have to pass the first parameter, which is by default 'canonical':

```
$entity->getTranslation($language)->url('canonical', ['absolute' => TRUE]);

```

`url()` is deprecated, so better use `toUrl()`:

```
$entity->getTranslation($language)->toUrl('canonical', ['absolute' => TRUE])->toString();

```

---
Tags: 8, uri
---


# Question
Title: How to get an export option as a pdf for views?
I am using views on my Drupal site I can able to export my view in csv, but I am not able export my views as pdf I need to export my view as pdf. Any suggestions on this it will be very helpful, Thanks in advance.

# Answer
> 0 votes
Try Views Pdf module

**Description of viewspdf module:**

> With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.
>
> There are already some PDF solutions such as Print. But these solutions use the HTML output and converts this to PDF. The downsides of such an integration are:
>
> No control over page flow (e.g. page break). Little or no control over page header and footer. You need HTML skills to change the layout. The rendering is slow and need a lot of memory, because it needs to render the HTML. Complex tables make troubles. Vector graphics can not be implemented, therefore the printing of the document can be problematic. You are limited by HTML's capabilities. No hyphenation.
>
> You can also specify a background PDF document. This enables you to put unlimited static content to the dynamic PDF. This static PDF can be exchanged dynamically by using a File Field. The PDF can be created by any PDF creator such as Adobe Acrobat Professional or Open Office.

---
Tags: views, files
---


# Question
Title: Solr ignoring NOT but works with "-" and "!"
I have a apachesolr module which works well except in one case. I'm not sure what happens when `NOT` is entered in query, it behaves as `OR`. It even works for `!` and `-` case.

For eg.

```
"apple" -"orange" //Results that only has "apple" but not "orange"
"apple" NOT "orange" //Results all the entities that has either "apple" or "oranges"

```

I have the a very similar installation on another site which seems to work without flaw. Any thoughts on what might be causing this?

# Answer
Issue was with my implementation. Before the query was posted to Solr, I was doing following:

```
$query = strtolower($query);

```

This made the `NOT` to `not` hence it wasn't working as expected.
> 0 votes

---
Tags: search
---


# Question
Title: Send email to specific user by using webform
**Send email to specific user :**

For this i have added a webform **contact to this person** using webform.

after filling the information in webform by anonymous user , a mail should be sent to that user whose profile is he/she seeing.

**Note**: this functionality should only work for anonymous user and by using webform.

How to achieve this?

# Answer
> 2 votes
Finally i found the solution by myself

1) Create a hidden field in webform say **username** field.

2)then go to /webform/emails .select the component value that is equal to **username** hidden field you previously created.then edit added component value in **E-mail from address section** select the component radio button instead of Default: abc@yahoo.com radio button.

3)**then create a custom module add this code**

```
 function your_module_form_alter(&$form, &$form_state, $form_id){

 if ($form_id == 'your_webform_id') {
    $uid = arg(1);
   if ( arg(0) == 'user' && is_numeric($uid) ) {
       $account = user_load($uid);
        $form['submitted']['Your-hidden-field-machine-name']['#value']   = $account->mail;
     }
   }

   }

```

---
Tags: 7
---


# Question
Title: What might cause my "User error" in Watchdog?
I'm trying to figure out the reason behind this "User error" in watchdog

```
User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 102 of /core/lib/Drupal/Core/Render/Element.php).

```

This error comes when I access any non-existing entity like

`myentity/762574527` or `myentity/anything`

On googling, I got this link , which states its due to `Token` module.

I uninstalled this module and deleted every content related to it, still this error persists.

Can anyone tell the reason behind this error?

# Answer
This is not connected to the Token module.

You should not try to render a non existing entity. Your code should throw an exception instead:

```
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

  throw new NotFoundHttpException();

```

Or configure the route so that when you have a non existing entity as parameter in the route, drupal will throw this exception automatically. See the answer from Berdir to your last question:

https://drupal.stackexchange.com/a/205054/47547
> 3 votes

---
Tags: 8, entities
---


# Question
Title: How to set a specific date (fixed value) as default value on a date field?
I have a commerce order on which I have added a date field. The options for the default value are **Now** or **Relative**. How can I add a fixed default value, f.x. **20 Aug 2016**?

# Answer
Since, it isn't clarify about if the datefield is asking you for a PHP code or not; you can just use this:

```
2016-08-20

```

In that way the field will change that date into what you want.
> 1 votes

---
Tags: 7, entities, datetime
---


# Question
Title: How to display a block for some paths but not if they match some other path also?
Let's say I have nodes with the following paths:

```
/chapters/university-of-florida/classrooms/class1
/chapters/university-of-chicago/classrooms/class2
/chapters/ucla/classrooms/cla

```

I'd like to display a custom block I created on these URLs, but I don't want it to show on:

```
/chapters/university-of-florida/
/chapters/university-of-chicago/
/chapters/ucla/

```

Any ideas how to accomplish this? Note that there will be new chapters and classrooms being added all the time, so I don't want to have to manually specify the paths.

I think the Context module could work here, but I am not sure how to specify the exclusions...

Any tips?

# Answer
The block control for "Show block on specific pages" supports wildcards and should work here, iirc.

Show only on these pages:

/chapters/university-of-florida/classrooms/\*
> 0 votes

# Answer
You could use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***". So that the block is only shown on the pages with the (first 3) paths you mentioned, and not on the (last 3) paths were you want to hide that block.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_show_on_selected_paths" : {
    "LABEL" : "Show block on selected paths",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "AND" : [
          { "OR" : [
              { "text_matches" : {
                  "text" : [ "site:current-page:path" ],
                  "match" : "\/chapters\/university-of-florida\/classrooms\/class",
                  "operation" : "starts"
                }
              },
              { "text_matches" : {
                  "text" : [ "site:current-page:path" ],
                  "match" : "\/chapters\/university-of-chicago\/classrooms\/class",
                  "operation" : "starts"
                }
              },
              { "text_matches" : {
                  "text" : [ "site:current-page:path" ],
                  "match" : "\/chapters\/ucla\/classrooms\/cla",
                  "operation" : "starts"
                }
              }
            ]
          },
          { "OR" : [
              { "NOT data_is" : {
                  "data" : [ "site:current-page:path" ],
                  "value" : "\/chapters\/university-of-florida\/"
                }
              },
              { "NOT data_is" : {
                  "data" : [ "site:current-page:path" ],
                  "value" : "\/chapters\/university-of-chicago\/"
                }
              },
              { "NOT data_is" : { "data" : [ "site:current-page:path" ], "value" : "\/chapters\/ucla\/" } }
            ]
          }
        ]
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

This Rules Component will make the block visible on any pages with a path that matches any of the first 3 paths you mentioned, provided such page does not have a path that also fits any of the last 3 paths you mentioned.

You could further enhance the above Rules Component (to make it more generic), by just replacing the Rules Conditions in it with something using an appropriate regular expression (related to the current path also). That would also help to reduce the need "*to manually specify the paths whenever new chapters and classrooms are added*" (as in your question).

Remark: the previous answer is incorrect ... the block would for sure not show on "`chicago`" or "`ucla`" related paths that also contain "`classrooms`".
> 0 votes

---
Tags: blocks, path-aliases
---


title: Drush cr command error's

text:
# Question
Title: Drush cr command error's
I am using drush for drupal `caches clear`, module enable/disable and so more commands. My drush version is 5.4, it working fine for `drupal 7` but now i creating new product in `drupal 8`. I am using same `drush` commands for `drupal 8`. but I am facing below problems.

> D:\Drupal\site\website\docroot\>drush cr PHP Fatal error: Class 'Drupal\Core\StringTranslation\PluralTranslatableMarkup' not found in D:\Drupal\site\website\docroot\core\includes\common.inc on line 132 Fatal error: Class 'Drupal\Core\StringTranslation\PluralTranslatableMarkup' not found in D:\Drupal\site\website\docroot\core\includes\common.inc on line 132 Drush command terminated abnormally due to an unrecoverable error. ?\[31;40m?\[1m\[error\]?\[0m Error: Class 'Drupal\Core\StringTranslation\PluralTranslatableMarkup' not found in D:\Drupal\site\website\docroot\core\includes\common.inc, line 132

# Answer
> 1 votes
There is a handy chart in the Drush documentation that will explain compatibility of Drupal versions to Drush versions.

Drupal 8 requires Drush 8.x running on PHP 5.4.5+ and that is compatible with Drupal 6 and 7 as well.

Edit: Duplicate of @greg\_1\_anderson's answer https://drupal.stackexchange.com/a/155103/42650

---
Tags: 8, drush
---


# Question
Title: Programatically redirect to node/nid doesn't redirect to url alias
From what I understand the module 'GlobalRedirect' has been merged into the 'Redirect' module. So the redirect module should also redirect links as node/nid to it's url alias. When creating redirects trough the interface this works perfectly. But if I programatically do a redirect to a node/nid page it isn't being redirected to it's url alias.. Not sure if this is bad coding on my part, or feature not implemented in the module.

```
  /* @file EventSubscriber.php */

  public function onRequest(GetResponseEvent $event) {
    $baseUrl = $event->getRequest()->getBaseUrl();
    $attr = $event->getRequest()->attributes;
    if(null !== $attr && null !== $attr->get('node') && $attr->get('node')->get('type')->getString() == 'product_group' &&
    $attr->get('_controller') == '\Drupal\node\Controller\NodeViewController::view') {
      $node = $attr->get('node');
      $references = $node->get('field_references');
      $values = $references->referencedEntities();
      if($values){
        $nid = $values[0]->id();
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $event->setResponse(new RedirectResponse($baseUrl. '/' . $language . '/node/' . $nid));
      }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['onRequest'];
    return $events;
  }

```

I'm using this code to redirect a product group to it's first referenced entity node, which uses automated url structure generated by a pathauto pattern, but the url alias isn't being shown after the redirect, it shows node/nid. I've verified that the url alias on that page actually works, and even added a redirect from that specific node/nid to it's url alias trough the interface, but no luck.

Am I doing something wrong? Is this working as intended? Is there a cleaner/better way for me to redirect? Still quite new to Drupal 8..

Using:
Drupal 8.1.3
Redirect 8.x-1.0-alpha1
Pathauto 8.x-1.0-alpha3

# Answer
> 6 votes
Try using Url.

```
$url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()]);
new RedirectResponse($url->toString());

```

---
Tags: 8, redirection, path-aliases
---


title: Use taxonomy path-alias

text:
# Question
Title: Use taxonomy path-alias
I've been working playing with the Facet API Search lately and I liked a lot the option that Facet API provides to use the alias of the taxonomies in the URL.

I was wondering if there is a chance to do the same in the Views. eg to be able to use the taxonomy alias as a token to construct a link. What I would like to achieve is to be able to construct in the Views a URL that can take me to a Faceted Search page so I can pre-filter it.

I know that is a bit redundant to be doing it, but for the project I work on, is something that was specifically requested. In the Views, there is no way to be able to get the alias of a taxonomy as a field. The only things I've seen so far, is to mimic the re-writing of taxonomy using PHP code here and here.

I tried to find a module that would help use the alias but nothing had come up. Also, here in the forum, I had found similar issues but nothing related to my question about taxonomies.

How to filter a View with Taxonomy alias

Get a node alias as a field value

# Answer
> 0 votes
Nevermind, I managed to do this via a module I wrote.

To whom it may concern, the idea is to create a hook override for the hook field formatter.

---
Tags: views, taxonomy-terms, path-aliases
---


# Question
Title: Text (plain, long) automatically has line break converted to <br>
I have created a field Text(plain, long) and have a custom template which currently only outputs this field.

```
{{ content.field_testing }}

```

When the output is rendered, all the line breaks are converted to `<br>` I need to remove. I could add some filters but I figure there must be a way to prevent it in the first place. How can I do this?

# Answer
> 5 votes
Since you are using a custom template, the quicker way is just to use the `replace()` filter.

```
{{ content.field_testing|replace({'<br>': '', '<br />': ''}) }}

```

The field formatter used in the case of a plain text field doesn't have settings, so you cannot decide if the formatter should output the `<br />` tags you want to remove. It would probably make sense in few cases, especially if you need to replace those `<br />` with other text, but somebody could argue that if you don't need them, you could just avoid entering new lines in the field.

The alternative would be implementing a different field formatter, but this is not as quicker as using a filter. If you just need this for this exact purpose, it sounds a bit excessive.

# Answer
> 2 votes
The default FieldFormatter for Text(plain, long) is BasicStringFormatter, and it does this:

```
$elements[$delta] = [
    '#type' => 'inline_template',
    '#template' => '{{ value|nl2br }}',
    '#context' => ['value' => $item->value],
  ];

```

You could overwrite it without the nl2br.

# Answer
> 0 votes
Finally i created a new formatter

```
<?php
  namespace Drupal\inception\Plugin\Field\FieldFormatter;

  use Drupal\Core\Field\FormatterBase;
  use Drupal\Core\Field\FieldItemListInterface;

  /**
   * Plugin implementation of the 'basic_string_no_br' formatter.
   *
   * @FieldFormatter(
   *   id = "basic_string_no_br",
   *   label = @Translation("Plain text No BR"),
   *   field_types = {
   *     "string_long",
   *   },
   * )
   */
  class BasicStringNoBrFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items,   $langcode) {
      $elements = [];

      foreach ($items as $delta => $item) {
          // The text value has no text format assigned to it, so the user input
          // should equal the output, including newlines.
          $elements[$delta] = [
              '#type' => 'inline_template',
              '#template' => '{{ value }}',//Plain value without nl2br
              '#context' => ['value' => $item->value],
          ];
      }

      return $elements;
  }
}

```

---
Tags: theming, 8
---


# Question
Title: Hook into Web-Form POST to send another POST request to 3rd Party Server?
The site I am working on has multiple *Contact us* type forms that are using a web-form plugin. They have a contact form that is on every page, 1 to 2 times per page. This contact form saves to the back-end and database when submitted.

Below is the basic form without the form elements.

```
<form action="/" accept-charset="UTF-8" method="post" id="webform-client-form-9" class="webform-client-form" enctype="multipart/form-data" _lpchecked="1">
  <input type="hidden" name="Provider" value="YourLeadSource">
  <input type="hidden" name="Client" value="L360">
  Fname: <input type="text"  name="fname" value="John"><br />
</form>

```

Now I have been tasked with keeping the current functionality, posting and saving to the database, but also adding new functionality to make it also POST or GET the same form submission to a third party site called leads360.

I need to have it also send a POST or GET request with the form data to https://secure.leads360.com/Import.aspx?Provider=TeledirectBusinessName&Client=CompanyName&CampaignId=12345.

In theory this should be really easy, if I can hook into the system and send a POST or even a GET request to that URL which will then post data into the third-party system.

The problem is my limited knowledge of Drupal. I know its plugin/hook system is nothing like WordPress or Magento.

Would you use some sort of hook in the backend, or intercept the post with JavaScript the way the Stripe API does for payments?

# Answer
There's the Webform Remote Post module that does exactly this.
> 2 votes

# Answer
Yes you'd use a hook in the backend, in a custom module. Just to confuse things a little bit more, the type of hook you need to implement (an 'alter' hook) can also be implemented in a custom theme. But I'd advise sticking with the custom module for this, as the functionality you need is beyond what a theme should really be responsible for.

For the low down on Drupal hooks in general, see What is the basic concept behind hooks?.

In your specific case `hook_form_alter()` will do the trick; as the name suggests it's used to alter a form. There's even a more specific version, `hook_form_FORM_ID_alter()`, which lets you alter a form with a specific ID.

To run custom code on form submission, you need to add a submit handler to the form like in the following example:

```
function MYMODULE_form_webform_client_form_9_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYMODULE_send_3rd_party_data';
}

```

The handler is just the name of a standard PHP function that you'll write, by convention prefixed with the name of your module. When the form is submitted, the function will run. In that function, you'll need to inspect the `$form_state['values`\]\` array, which contains the user-submitted values from the form.

```
function MYMODULE_send_3rd_party_data($form, &$form_state) {
  // Examples...
  $name = $form_state['values']['name'];
  $age = $form_state['values']['age'];
}

```

From there it's just a matter of submitting the data to the 3rd party service with the method of your choice. cURL is an obvious option, but Drupal also provides the `drupal_http_request()` function if you'd prefer to stay within the API.
> 1 votes

---
Tags: webforms
---


title: How to handle complex test results?

text:
# Question
Title: How to handle complex test results?
Actually we are using D7 mostly for books and book pages like manuals.

We would like to link files like PDF and Excel to a Drupal book page but we have no experience how to manage to open those files from drupal or view their content in drupal.

Therefore I would appreciate instructions for eventually necessary modules and settings.

We have a browser extension in chrome for PDF and see them directly in the browser , but from a Drupal page (localhost:8080/drupal/?q=it/node/398`), the link to that PDF first gets me to another page (`drupal/?q=media/1242\`) and I have to click again on the PDF icon to open it in the browser. Thaty's somewhat annoying. Can anyone please indicate a direct way for PDF and for Excel files? Is it necessary to fit the browser for Excel? if yes, how?

# Answer
> 1 votes
Instead of "*... save the differences in an Excel table ...*", you might want to consider saving these data in an external database (MS SQL, MySql, Oracle, some PDO compliant database, etc).

And then use the Forena module to build custom queries to retrieve the data (directly from such database) and create custom reports from them. Those reports can then be exported in PDF or Excel. For that you just have to enable the desired Forena report options called "document format".

Refer to my answer to "How to download Database results as PDF or in EXCEL" for more details.

---
Tags: 7, files
---


title: One Time Bulk Node Creation

text:
# Question
Title: One Time Bulk Node Creation
I have Drupal 8 site I need to migrate a bunch of data into from a different CMS. What I'd like to do is write a basic SQL query and iterate through the results, creating a new node for each returned row.

Since it's a one time thing - do I need to write a full module for this - or can I just hook into drupal some other way (like through the main index.php file) and do the node::create(\[\]) $node-\>save() stuff from within there?

Never done something like this before - and looking for the easiest way. Any help/guidance is appreciated!

# Answer
You don't need a "full" module for this, you can do this with two files and a few lines of code:

modules/myimport/myimport.info.yml:

```
name: myimport
description: 'My import module'
core: 8.x
version: 8.x-1.x-dev
type: module

```

modules/myimport/myimport.module:

```
<?php
use Drupal\node\Entity\Node;
function import_stuff() {
  // fetch data
  foreach ( $data as $row ) {
    $node = node::create([]);
    $node->save();
  }
}

```

You can start the import from anywhere in drupal or from the command line with drush:

```
drush ev 'import_stuff()'

```
> 0 votes

# Answer
Your options are:

1. Feeds module - You can check the doc here.
2. Export the content from source into csv or json. On the target (D8) either you can use Migrate module to handle the migration but requires custom coding.
3. Create a json endpoint that will expose the content and in your target (D8) server consume that endpoint. You can then get the content by using `Guzzle`.

Example...

```
$request = Drupal::httpClient()->get($url);

```

See this page for more info.

**P.S:** I have no experience building with D8 yet but my suggestions above I guess is still applicable.
> 0 votes

# Answer
If it's a bunch of data, it's probably best to use the migrate module.

I've recently a migration with migrate\_plus, which comes with a migrate\_example module you can copy. There's a yml file and a class for BeerNode that you can pretty much copy.

Then, set up your other database in settings.php:

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

```

Then, you can specify the source in the yml file for your importer.

```
  source:
    key: example_other_db

```

Then you basically map the fields to custom keys within your migrate class (see BeerNode.php in migrate\_example module)

Here's some examples from my recent migration:

```
  field_copyright_year: copyright
  field_isbn: ISBN
  field_volume: volume
  field_pages_length: pagesLength
  field_pub_title: bookJournalMagazineTitle
  field_edition: edition
  field_short_place: placePublished
  field_shelf_code: callNumber

```

If you need something complex like an address field you can build it in your class, so the custom key is an array that matches what addressfield expects. There's a prepareRow function where you can do other queries

```
  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {

    $row->setSourceProperty('companyName', $this->cleanString($row->getSourceProperty('companyName')));

    $address = [
      "langcode" => "EN",
      "country_code" => "US",
      "administrative_area" => "US-" . $row->getSourceProperty('state'),
      "locality" => $row->getSourceProperty('city'),
      "dependent_locality" => NULL,
      "postal_code" => $this->cleanString($row->getSourceProperty('zip')),
      "sorting_code" => NULL,
      "address_line1" => $row->getSourceProperty('address1'),
      "address_line2" => $row->getSourceProperty('address2'),
      "organization" => $row->getSourceProperty('companyName'),
    ];

    $row->setSourceProperty('address', $address);

    return parent::prepareRow($row);
  }

```

Then you run the migration from the command line.

1) run "drush ms" and make sure it lists your migration

2) run "drush mi example\_migrate\_machinename"

3) to pause import, do "drush mst example\_migrate\_machinename"

4) for other commands you can run " drush | grep migrate"
> 0 votes

---
Tags: 8
---


title: How to delete stuck batch?

text:
# Question
Title: How to delete stuck batch?
What is a good way to delete a stuck batch in Drupal 7?

It is on a production server, we are using the Background Batch module so it shows us which one it is at admin/config/system/batch/overview.

I know I can just run a query and delete that row from the DB but wondering about other cleanup I should do too.

# Answer
> 6 votes
Another approach (if you don't want to run sql-statements directly) would be Queue UI:

> * View queues and number of items
> * Developers can define meta info about queues they create and process
> * Process queue with Batch API
> * Process queue during cron
> * Remove leases
> * Delete queue

# Answer
> 3 votes
In my case the batch ID is 5166:

`DELETE FROM batch WHERE bid IN (5166);`

In our case we are using Better Batch and we also needed to run:

`DELETE FROM better_batch WHERE bid IN (5166);` otherwise we received an infinite redirect message in Chrome "too many redirects".

source: https://www.drupal.org/node/1627850#comment-6142774

---
Tags: 7, batch-operations
---


# Question
Title: How to change the email recipient for contact form
On a Drupal 8 site, I have a content type called TeamMember which has an email field. From the view where I show all the TeamMembers, I'd like to link to a form where the user can email that person directly. Is there a way to customize the recipient of the email from a contact form?

# Answer
> 2 votes
What we do in a few places is to have a hidden reference field to the team node in your contact message entity.

Then you pre-fill that when displaying the contact form and later on in hook\_mail\_alter(), use that information to change the recipient.

Requires a bit of custom code but then you don't have to create a lot of contact forms.

# Answer
> 1 votes
Contact forms in D8 don't have customizable recipients out of the box so you're going to need some sort of workaround.

A couple of paths that you could take:

1. Treat your *TeamMember* not as *Node* entities, but as *User* entities. Use their profile page (**/user/X**) as the content page and use the personal contact form (**/user/X/contact**) as the per-*TeamMember* contact form.
2. Keep the *TeamMember*, but create a unique contact form for each *TeamMember*. On the *TeamMember* node type, create a Link field that links to each unique contact form you've built.

---
Tags: 8, emails
---


# Question
Title: How to show a block on user/uid but not on user/login and user/registration?
I have public profiles for my users at `/users/1` etc and show blocks on that page with the setting "Only the listed pages" of "user\*".

Now those blocks also appear on `user/login` and `user/registration` pages.

How can I exclude blocks from those 2 pages?

Otherwise I'll probably use the Pathauto module to have the user profiles at `/profile/...`.

# Answer
> 2 votes
Enable the PHP module, and use this for block visibility settings:

```
<?php
return (bool) menu_get_object('user');
?>

```

# Answer
> 1 votes
I would try to use the Context module here.

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.

# Answer
> 0 votes
There is another way to answer your question ***without PHP in the block settings*** (as suggested in another answer), and without using the Pathauto module: you can use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown on your pages with a path that **starts with** "`user/`", but not on those pages that have a path **ending with** "`/login`" or "`/registration`").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_show_on_selected_member_pages" : {
    "LABEL" : "Show block on selected member pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "AND" : [
          { "text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "user\/",
              "operation" : "starts"
            }
          },
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "\/login",
              "operation" : "ends"
            }
          },
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "\/registration",
              "operation" : "ends"
            }
          }
        ]
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

---
Tags: 7, blocks
---


title: Get URL of Views 'file' field

text:
# Question
Title: Get URL of Views 'file' field
How can I get just the url of the uploaded file from the Views module 'file' field. If I do the following:

```
print $view->render_field('field_url', $id);

```

I get the entire 'file' object in html format. How can I retrieve just the url of the uploaded file?

# Answer
> 0 votes
If you use the Image URL Module module you can set the field to 'Image URL' format and call it with

```
$fields["field_name"]->content

```

and it should only output the url to the image without any surrounding html

---
Tags: views, files
---


# Question
Title: How to show a block on a set of subpages except one of them?
I have a block which is shown on all subpages under "`mypagename`", using the following bmock visibility settings:

```
Only the listed pages --> mypagename/*

```

Except I now need to exclude one page under "mypagename" for showing this block. Is there a way to easily exclude this page using the standard settings of Drupal 7?

# Answer
There's nothing in the core UI, no.

`hook_block_list_alter()` exists for exactly this sort of scenario, though:

> Act on blocks prior to rendering.
>
> This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.

e.g.

```
function MYMODULE_block_list_alter(&$blocks) {
  if ($some_condition) {
    // Remove the block from the list.
    unset($blocks[$some_key]);
  }
}

```
> 2 votes

# Answer
Sometimes it may be feasible on the theme level. What blocks I need depends more on type of content than on it's URL, and I do find that for specific subpage I don't need some blocks, whilst I need them for others.

In such cases I simply create a region I output where I need it and don't output where I don't. Main benefit is: I do not need to iterate over configurations and update them when I restructure my page. I only need to update theme. And pretty often I don't really need even that.

Similar benefits are possible with Clive's answer, too, if you take care about setting `$some_condition` properly.
> 0 votes

# Answer
There seems to be nothing in core, indeed. However, apart from writing your custom module, you can also use the Rules block visibility module as an alternative (and which ***doesn't require the PHP filter to be enabled*** either, which you should try to avoid whenever possible). Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown on your pages with a path that **starts with** "`mypagename/`", but not on a subpage with a path (say) "`mypagename/exception`").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_show_on_selected_subpages" : {
    "LABEL" : "Show block on selected subpages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "AND" : [
          { "text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "mypagename\/",
              "operation" : "starts"
            }
          },
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "mypagename\/exception"
            }
          }
        ]
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

**Note**: have a look at the rules\_block\_visibility.module code also. And notice how it also implements `hook_block_list_alter()`. So using this approach you have a lot of the Rules (Conditions) power available also.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Connect Content Type with Related Taxonomy Fields using Template
I have a Content Type displaying correctly using a template, pulling out the fields to appropriate locations.

I now want to pull in related information from two separate taxonomies. I have a term reference to each Taxonomy setup as a field in the Content Type.

I have the taxonomy fields mapped out in the template, but the output is empty. I believe it is because I need to define a relationship somehow.

My current direction is to create out a view using EVA and render it to the template (which is poor for performance), but I am struggling to figure out how to define the relationship to the node.

Please provide examples of how you would approach this problem.

For context, Content Type is a job listing. Taxonomy B is information about the respective company. Taxonomy C is information about the respective city the job is in. Both Taxonomies can be made into Content Types if that helps.

# Answer
> 0 votes
I solved this by creating two new regions in my theme underneath Content, then I created a View with two blocks: one for taxonomy B and one for taxonomy C.

The view pulls in taxonomy fields using the relationship: `Content: Taxonomy terms on node`.

I have setup the URL pattern for my content type to be `contentTypeA/taxonomyB/taxonomyC`. By doing this, I was able to reference the correct term by using a Contextual Filter: `Content: Has taxonomy term ID`.

The Contextual Filter was a little tricky for me. As it was coming from the URL at a specific level of the path, I found that I could access taxonomyB through the `path component 2`, and taxonomyC through `path component 3`.

Under `WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED` I used `Specify validation criteria` as the respective taxonomy term.

Finally, using `Term name converted to Term ID` allowed it to see the plain english term name in the URL path.

---
Tags: 7, theming, taxonomy-terms
---


title: Display mode for search API users index

text:
# Question
Title: Display mode for search API users index
I have Search API users index. I am trying to show them in views with my display mode (for example 'teaser') created by Display Suite.

But I only can show fields. For default user view I can show all modes: fields, display suite, rendered entity and so on.

How I can show them via rendered entity?

# Answer
> 3 votes
This worked for me:

1. Clear the site's cache (drush cc all)
2. Re-index the search api index that powers the view
3. Refresh the view edit page

After that you should see the "Rendered entity" option appear with your view modes as options.

# Answer
> 0 votes
Check out this View php

put custom code in it and fetch data from database using predefined variables in it

---
Tags: views, search, display-suite
---


title: Call fieldset multiple times

text:
# Question
Title: Call fieldset multiple times
I am using webforms in Drupal7, i give the user the option to enter multiple entries for one question. So for example, "how many players", if answer is 1, fieldset 1 opens and has name, address, number in it.

if answer is 2, fieldset 1 and fieldset two appear, if answer is 3, fielset 1, fieldset 2, and feildset 3.

if the answer is 2 or 3, I get this error: Conditional errors on page 2: More than one conditional hides or shows component "One Player". More than one conditional hides or shows component "Two Player".

so my plan was to create 10 fieldsets and have them display based on the # of players the user inputs. I understand the error, but don't know of another way to achieve this. \[the one I came up with is just crazy and would mean so many of these inside fields, OMG \]

Any suggestions / guidance, would be appreciated.

# Answer
For anyone else that stumbles on this. I found a solution. So remember my example is "How Many Players" \[i used select option 1-5\]. If user selects 1, fieldset 1 appears only, if he/she selects 2, FS1 and FS2 appear, select 3, FS1, FS2 and FS3 appear. To prevent the error I use and or statement for allow the fieldset and worked my down down. See image.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Adding markup to fields in block plugins
I'm attempting to create a block plugin that renders nodes retrieved from a query. I'm able to successfully get the node id's and field values from the query but I'd like to wrap each item in divs and classes but I'm not sure where to start.

```
public function build() {
    $query = \Drupal::entityQuery('node')
        ->condition('type', 'blog_post')
        ->sort('created', 'DESC')
        ->range(0,3);

    $nids = $query->execute();
    $build = [];

    foreach ($nids as $nid) {
        $node = Node::load($nid);
        $build[] = $node->field_image->view();
    }

    return $build;
}

```

This is able to render a list of images. But I'd like to be able to have control so I can output something like

```
<div class="column">
    <div class="image">
        <img src="img1.jpg">
    </div>
    <div class="bodytext">
        <p>Body Text</p>
    </div>
</div>

<div class="column">
    <div class="image">
        <img src="img2.jpg">
    </div>
    <div class="bodytext">
        <p>Body Text 2</p>
    </div>
</div>

<div class="column">
    <div class="image">
        <img src="img3.jpg">
    </div>
    <div class="bodytext">
        <p>Body Text 3</p>
    </div>
</div>

```

Instead of what Drupal wants to output automatically from the view() function.

# Answer
> 0 votes
You can configure a custom view mode with the two fields image and body and then use a twig file:

```
node--blog-post--my-view-mode.html.twig

```

And build the node:

```
$build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'my_view_mode');

```

Alternatively your task could be easily solved in Views, but maybe this is only an simplified example and you need to do more things in code.

---
Tags: nodes, 8, plugins
---


title: How can I download code from Github?

text:
# Question
Title: How can I download code from Github?
I'm still running some Drupal 6 sites (because I'm waiting for the Migrate module to work properly in Drupal 8), and I notice that there are some modules in rupal D6 (like Views) which are still bringing out security releases. However, since the code has been moved off drupal.org, these new releases are not getting downloaded by Drush when I do a pm-update to install security releases.

Is there any way to tell Drush to look on Github for certain modules? Alternatively, is there a git command to do this?

# Answer
The git command is `git clone`. You would type:

```
git clone <repository-url> path/to/modules/module_name

```
> 0 votes

---
Tags: drush, version-control
---


# Question
Title: Can we upgrade a site directly to latest version (without an extra fresh site)?
As far as I understand, the only way to upgrade Drupal (core-only) sites today is with **having two sites**: One is the *Drupal 7* site with its own folder, and another which is a fresh *Drupal 8* site in another folder; We then enable the core-based Drupal 8 migration modules in the fresh Drupal 8 site and with them Migrate-upgrade the Drupal 7 site into that fresh site.

Is there a way, maybe with Drush or with Drupal console, to actually Upgrade the existing Drupal 7 (core, or core&Ctools&Views) site directly as it is, without actually opening a fresh Drupal 8 site, besides it?

In other words, can we use the Console or Drush to update an existing Drupal 7 site directly, without any kind of migration?

# Answer
> 5 votes
No.

The old method of upgrading Drupal through **update.php** has been dropped in Drupal 8 in favor of the Migration framework & UI. The idea here is to provide a clean way into a new database schema without any problems of **update.php** trying to accommodate many diverse scenarios (as it was prone to do with moving complex sites from D5 to D6 & D6 to D7).

D8 has some significant changes to its architecture; trying to patch code & alter the DB schema for a D7 site to move it to D8 could be fraught with problems. It could theoretically be done, but you'd probably spend more time doing that than to just devise a content / custom code migration path.

For more information read *Upgrading from Drupal 6 or 7 to Drupal 8* on drupal.org.

---
Tags: 8, upgrading
---


# Question
Title: Count total number of values in a field of all nodes combined for a view
I need to count the number of entries made to a field in all nodes combined together.

I tried toggling aggregation to 'yes' and aggregation type to 'COUNT as distinct'. But at that time I'm getting count for each node separately. But What I really need is a single line output saying this much of entries made to this field for the whole nodes combined together.

The after that I will be able to filter it by 'id from logged in user' or 'date created'.

# Answer
> 2 votes
There is a module to assist with that: Views Field

> Allows field tables to be used as base tables with Views.

After you installed the module you need to visit the field setting on any content type that includes the field. **Tick** `Expose as base table`, then select all the columns to expose excluding revision\_id.

Next create a view and at `admin/structure/views/add`at Show listbox you select the Field base table. This will now create a view on the field in question's base table.

Your view settings should have these settings:

* Use aggregation: Yes
* Fields: Entity Type (The entity type this data is attached to) with Aggregation setting Count.

You can now add Relationship: Field tables: Field XXX =\> Node to get access to the nodes the fields are attached to and from there author etc.

**ALTERNATIVE**

Create a View of Content (ie nodes) showing fields. Set Aggregation to Yes. Remove sort Criteria, filter criteria and Pager. Add your field's delta (Delta - Appears in: node:xxx.) to the View fields with aggregation set to COUNT.

---
Tags: views, entities
---


# Question
Title: Create a field collection field programmatically
Is there a way to create a field collection programmatically? I saw this code:

```
$field_collection_item = entity_create('field_collection_item', array('field_name' =>'field_text')); // Create new field collection item.
$field_collection_item->setHostEntity('node', $node); // This is required, there shuold be a host entity, this case I used a node.
$field_collection_item->field_text[LANGUAGE_NONE][0]['value'] = 'Test Value';
$field_collection_item->save(); // Save the field collection item.

```

But when I run this code I get this error:

> Exception: Invalid field name given: field\_text is not a Field Collection field.

I can't find a proper solution for this.

# Answer
Have you tried using entity metadata wrappers? They come with the Entity API module and allow you to do this (copied from linked documentation):

```
<?php
    // Populate the fields.
    $ewrapper = entity_metadata_wrapper('node', $node);
    $ewrapper->field_lead_contact_name->set($contact_name);
    $ewrapper->field_lead_contact_phone->set($contact_phone);
    $ewrapper->field_lead_contact_email->set($contact_email);

    // Create the collection entity and set it's "host".
    $collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
    $collection->setHostEntity('node', $node);

    // Now define the collection parameters.
    $cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
    $cwrapper->field_facility->set(intval($offset));
    $cwrapper->save();

    // Save.
    $ewrapper->save();
?>

```

In this example a node and the attached fieldset are created at the same time, so it might just work with only below code. Perhaps it is required to save the node afterwards, I have not tested it.

```
<?php
    // Create the collection entity and set it's "host".
    $collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
    $collection->setHostEntity('node', $node);

    // Now define the collection parameters.
    $cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
    $cwrapper->field_facility->set(intval($offset));
    $cwrapper->save();
?>

```

Update:

At the bottom of the Entity Metadata Wrapper documentation (before the comments) there are some lines about debugging and finding available parameters. That also might be of help while attempting to find the right property.
> 0 votes

---
Tags: 7, entities
---


title: Change date format on editing

text:
# Question
Title: Change date format on editing
I'm using a date field on my custom type, if I use "select" widget for node editing, I can choose only between "YMD","MDY" and "DMY" formats.

Is there a way to add custom formats? I need an "only year" format.

# Answer
> 4 votes
By default, no. The relevant code is in `\Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDatelistWidget::formElement()`.

What you want is usually called a "partial date", which is a bit of an oxymoron. In Drupal, datetime fields are stored as `DrualDateTime` objects, which derive from `\DateTime` so have both a full date and a proper time and timezone associated with them.

A partial date (year, year+month), has to make assumptions about the rest of the parts. For example, the date-only field currently sets the time to noon UTC. A year only field would have to do something similar.

You may be able to create your own widget for the datetime field to do this. You could take `DateTimeDatelistWidget` as a starting point, and trim it down to be just the year. Then, you would need a masssageFormValues() to set the rest of the parts and then call the parent method (because `DateTimeWidgetBase::masssageFormValues()` does stuff, too). This may or may not work, it is just the idea that popped into my head.

There is an open issue about this, https://www.drupal.org/node/2703037, that may or may not be implemeneted.

---
Tags: 8, datetime
---


# Question
Title: How to change the author and date of a new comment before posting it?
I am copying the content from my old non-CMS (Weebly) website to my new Drupal website by manually filling in node forms and comment forms. I would like to recreate all the original authors and posting times on the new website. As a first step, I have created a user account for all the people who contributed to the old website.

Adding nodes works perfectly: as an administrator, I can post new nodes as another user and change the posting time before publishing.

Now, I would also like to add new comments, and change the author and date before posting. I know that one can administrate a comment *after* posting it, as shown in the screenshot below.

However, it is vital that the desired changes are made *before* posting comments, since publishing triggers multiple Rules, related to User Points, Flags etc. Otherwise, the wrong users are rewarded User Points, for example.

How can I do that?

# Answer
> 1 votes
This is a small hack and it will show you some errors, but it works. In Drupal the comment form on the node is the exact same form as you'll see on the admin page you put in a screenshot. The visibility of fields is controlled by one variable `$is_admin` defined on line 1883 of modules/comment/comment.module:

```
$is_admin = (!empty($comment->cid) && user_access('administer comments'));

```

Basically this checks if the comment has a comment id (`cid`) and if the user may administer comments.

By removing the id check (so the condition also validates for new comments which not yet have a cid), the administration information is also shown for new comments (the user still requires the 'administer comments' permissions so regular users will not see it).

Thus line 1883 becomes:

```
$is_admin = (user_access('administer comments'));

```

You will get some warnings (notices) as these fields are not built for empty data (under normal circumstances they always have a value), but the submission works flawless. Just don't forget to change this back afterwards ;)

# Answer
> 1 votes
# Author

For changing the author (not the date), you might be able to use the Masquerade module for this. Some details from its project page:

> The Masquerade module allows site administrators (or anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time.
>
> This is helpful for site developers when trying to determine what a client, logged in as themselves, might see when logged into the site.
>
> The masquerade module is designed as a tool for site designers and site administrators. While masquerading, a field is set on the $user object, and a menu item appears allowing the user to switch back. Database log (watchdog) entries are made any time a user masquerades or stops masquerading as another user.

So just switch to the appropriate user before filling in your forms, that should do what you're trying to achieve.

PS: works for any currently supported release of Drupal.

# Date

Not sure (yet) about how to do this, but I'd try to use the Rules module for this. Here is a prototype of a rule that you may want to look at and experiment with:

```
{ "rules_update_comment_post_date" : {
    "LABEL" : "Update comment post date",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_presave" : [] },
    "DO" : [
      { "data_set" : { "data" : [ "comment:created" ], "value" : "-1 day" } }
    ]
  }
}

```

This rule should set the actual comment date to "current date - 1 day". Just as a sample. Adapt the value to fit your needs (before posting each comment, sorry ...), or try to think of an enhanced version of it to somehow retrieve the comment date as part of this rule.

---
Tags: 7, comments
---


# Question
Title: How can I set a variable based on the render element $vars[‘body’][‘#object’][‘vid’]?
In trying to learn about theming and alter hooks. I'm looking at the render array passed to `hook_node_view_alter()` with the following code.

```
function hook_node_view_alter(&$build) {
  dpm($build);
}

```

I want to set a variable based on `$build['body']['#object']['vid'])`, but I get this error:

> Fatal error: Cannot use object of type stdClass as array

I don't understand this error. Can someone explain it?

# Answer
> 1 votes
The #object in the $build array *is* an object, therefor it's properties have to be referenced with an arrow, -\>

```
$orig_vid = $build['body']['#object']->vid;
$build['body']['#object']->orig_val = $orig_vid;
$build['body']['#object']->vid = 100;

```

thanks Gulok for answering this

---
Tags: 7, theming, hooks
---


# Question
Title: Installation keeps complaining that Unicode library (mbstring) should be disabled, even though it seems it already is
I'm trying to install Drupal 8.1.3. (Apache 2.4.7, PHP 5.5.37, Windows 7)

In the "Verify Requirements" step Drupal keeps complaining

> Unicode library -- Error -- Multibyte string input conversion in PHP is active and must be disabled. Check the php.ini mbstring.http\_input setting. Please refer to the PHP mbstring documentation for more information.

However, I already have the following in my php.ini

```
mbstring.http_input = pass

```

and the diagnostic output produced by a call to `phpinfo();` contains

```
zend.multibyte  | Off | Off

```

So I am not sure whether

1. I was unsuccessful in switching off the multibyte string input conversion,
2. I am looking at the wrong configuration files / settings, or
3. Something is wrong with Drupal's detection of these setting (see for instance this discussion on a failing detection).

# Answer
http://php.net/manual/en/mbstring.configuration.php#ini.mbstring.http-input

Drupal's code is checking it in core/lib/Drupal/Component/Utility/Unicode.php, but it won't even check if unless PHP version is \< 5.6.0. If you are using PHP 5.5.x here's the check:

```
  if (ini_get('mbstring.http_output') != 'pass') {
    static::$status = static::STATUS_ERROR;
    return 'mbstring.http_output';
  }

```

So I would double check the phpinfo via the Drupal interface at /admin/reports/status/php to make sure you are changing the config file that's used by PHP for Drupal.
> 0 votes

---
Tags: 8, installation
---


title: Prevent block from caching

text:
# Question
Title: Prevent block from caching
I have a custom block that reads information from the database. As the user will be filling out a form, refreshing the page and viewing the block it cannot be cached. How do I fix this?

I have tried:

```
$build['#cache']['max-age'] = 0;

```

And this did not fix it.

I also tried copying the code from the custom block to the top of the form, so it runs as part of the page, here it doesn't cache. Unfortunately this isn't a solution as I need the block on another page also.

# Answer
> 1 votes
Drupal caches the already rendered block and doesn't check for changes in code, so after changing #cache in the block's render array as shown, you'd still need to use drush or the UI option to force-clear the render cache after changing this.

As an alternative, try deleting the block instance and placing it again.

Since you don't indicate that the form is making changes to the database, it's not clear if there is any cache tag to associate - is it data input or something more like a search form?

---
Tags: blocks, caching
---


# Question
Title: How to display the un promoted to front page link in teaser mode contextual links?
I'm trying to enhance the frontpage teaser's contextual links. On front page content we click on *Configure link*, and it shows *Edit*, *Delete* and *Node Export* by default.

I'd like to also add a *Unpromote from/to frontpage* link.

Is this possible? If so, how can it be achieved?

# Answer
Contextual links can be added by adding a menu item (e.g. `hook_menu()` or `hook_menu_alter()`) and setting `context` to `MENU_CONTEXT_INLINE` & `type` to `MENU_LOCAL_ACTION`. For node actions, you can add a menu item to the `node/%` route. The nid argument can be passed through so you can execute your appropriate node frontpage toggle logic.

For example:

```
/**
 * implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/%/frontpage'] = array(
    'title' => 'Toggle Frontpage Status',
    'type' => MENU_LOCAL_ACTION,
    'context' => MENU_CONTEXT_INLINE,
    'page callback' => 'MYMODULE_toggle_frontpage',
    'page arguments' => array(1),
    'access arguments' => array('administer content'),
  );
}

function MYMODULE_toggle_frontpage($nid) {
  // @TODO: Add your $node->promote switching logic.

  // Jump back to the original page containing the context menu.
  drupal_goto(drupal_get_destination());
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: What alternatives do I have to use the Computed Field module?
I am currently using the Computed Field module to calculate field in Field Collection and use PHP code to generate the formula. The problem is that the user does not enough PHP skill to write that PHP code. So are there any alternatives that allow users to choose which fields and calculations instead of using PHP code?

# Answer
Using rules you can do basic calculations with field values and write the result into an other field. If you do the calculation after an instance of your content type has been saved you make sure the value is always up to date.

Of course you can implement your own action as well and hook it into rules. See hook\_rules\_action\_info.

Whether your users find rules easy to manage and you can trust them to give them access to the rules system is an other story. Depending on what you want to evaluate you might just add some fields to get all the information you need and add a custom action to do the evaluation.
> 1 votes

# Answer
A not commonly known/used alternative to the Computed Field module, is the (fairly new) Math Field module (for D7). Some more details about this module (from its project page):

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

However, Math Field does not yet support Field Collections (#2573643: Support the Field Collection module). So in order for it to work in this specific case, you might have to rework the Field Collection you're using in something Math Field does support.

**Known issues**

As this is a fairly new D7 module, there are still a few other (known) issues with it, as mentioned also on its project page:

**Bonus**: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...
> 0 votes

---
Tags: entities
---


# Question
Title: Why can anonymous users see my block, whose visibility is set to hide it for anonymous users?
I have a block on one of my sites, in which all content is private. Anonymous users don't see any of my content types, any of my views, blocks, etc.

The problem is one single block. The problem block is the only one not created by a view or a module. I created it simply by adding it via the block page interface. I have set its visibility settings to be restricted to a certain role (not 'Anonymous', of course :-)).

However, this is the one piece of content that is still showing up on my site for anonymous users (before one logs in). I've cleared cache multiple times, so that isn't the issue.

Has anyone else run into this issue? Why would the block not respect the visibility settings? I'm wondering if there are some modules that may be interfering with this or if there's another explanation I'm not seeing....

# Answer
> 2 votes
The strangest thing fixed my issue. I'm still not sure why.

I was placing the block in a certain region with the 'Context' module. When I removed the block placement from that context and set it directly in the block's configuration page, the block stopped being visible to anonymous users.

Not sure why that would matter! Placing blocks generated by views with the 'Context' module is not interfering with their visibility settings, but for some reason it was interfering with this one. It's just a regular block with text, nothing funky.

In any case, that's what solved my problem...

# Answer
> 0 votes
I had a problem like that in my website which was caused by a totally unrelated module. In my case the coder module caused my admin page to break. But finding the module which caused the problem was very tedious. Just disabling the modules did not work. I had to move each module outside the modules folder, clear the cache and reload the webpage each time I did this. If the problem is caused by a module then you can make modifications as necessary.

# Answer
> 0 votes
As per your own answer, it seems that you're using the Context module. That helps to answer to this part of your question:

> Why would the block not respect the visibility settings? I'm wondering if there are some modules that may be interfering with this or if there's another explanation I'm not seeing....

Actually, the Context module does not check (take into account) the "*Block visibility settings*". If you want that to be the case, then you need to use the Context Respect module. Some details about this module, from its project page:

> Extends the Context module by making it respect default block settings.
>
> This makes it so you can retain your block visibility when assigning them into various Contexts. You can also 'Override' from the block level to ignore Context Respect.

### Alternative to context module

If you're using the Context module (only) to only show some block on selected paths (which you can't specify with the standard block visibility settings), then you may want to have a look at the Rules block visibility module as a valid alternative. Refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?" for more details about it.

By using this module as an alternative, you'd only have to create a Rules Component with Conditions to verify the path(s) on which to show the block, and to check the roles for which you want to show the block, it's that easy ...

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


# Question
Title: How to print entity referenced fields (node) title in node.tpl.php?
I want to print an entity referenced fields (node) title in `node--customtype.tpl.php`.

`<?php print render($content['field_my_entity_reference']); ?>` prints the field with some CSS class as below:

```
<div class="field-items">
<div class="field-item even">
<a href="/node/11">Entity Title</a>
</div>
</div>

```

What I want to do is to print this field **without any pre-defined CSS classes etc.**.

```
[field_my_entity_reference] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [target_id] => 11
                            [entity] => stdClass Object
                                (
                                    [vid] => 41
                                    [uid] => 1
                                    [title] => Entity Title
                                    [log] =>
                                    [status] => 1
                                    [comment] => 1
                                    [promote] => 0
                                    [sticky] => 0
                                    [nid] => 11
                                    [type] => project
                                    [language] => es
                                    [created] => 1466009429
                                    [changed] => 1466502663
                                    [tnid] => 0
                                    [translate] => 0
                                    [revision_timestamp] => 1466502663
                                    [revision_uid] => 1
                                    [body] => Array
                                        (
                                            [und] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [value] =>

```

I tried `<?php print $node->field_my_entity_reference['und'][0]['entity']['title']; ?>` but it gives error:

> Fatal error: Cannot use object of type stdClass as array in

## How can I print the title value of entity referenced field in node.tpl.php?

# Answer
OK, without knowing anything about `stdClass Object` these kind of questions are normal :)

So, after reading a question about stdClass Object in SO I did what I want as below:

```
<?php print $node->field_my_entity_reference['und'][0]['entity']->title; ?>

```

This prints the title as plain text.

*Note: Is there another way or better way you're always welcome.*
> 1 votes

# Answer
Alternative using the API is to use `field_get_items` and `field_view_value`.

Consider this example:

```
$field = field_get_items('node', $node, 'field_machine_name');
$title = field_view_value('node', $node, 'field_machine_name', $field[0]);
print render($title);

```

`$title` will produce...

```
Array
(
    [#markup] => test lang
    [#access] => 1
)

```

which is a renderable array.

The advantage of this against `print $node->field_my_entity_reference['und'][0]['entity']->title;` is the API will take care of the translation.

If you want to still use `print $node->field_my_entity_reference['und'][0]['entity']->title` I advice to avoid using `und` instead I will use`LANGUAGE_NONE` or much better `$node->language`.

```
print $node->field_my_entity_reference[$node->language][0]['entity']->title;

```
> 1 votes

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


title: Remove vertical tabs?

text:
# Question
Title: Remove vertical tabs?
I bought a module on Envato. I've already contacted the developer, but he does not respond. The module outputs some vertical tabs.

They are created with this code.

```
/**
 * Implements of hook_builder_content_info()
 */
function builder_builder_content_info() {
  $blocks = _block_rehash();
  $contents = array();
  if (!empty($blocks)) {
    foreach ($blocks as $key => $block) {
      $contents[$block['delta']] = array(
        'info' => $block['info'],
        'type' => 'block',
        'group' => t('Block'),
        // This is name of group to collect contents in a tab
        'block_module' => $block['module'],
      );
    }
  }

  // node add content
  $contents['node'] = array(
    'info' => t('Adding existing node'),
    'group' => t('Node'),
  );

  //Custom text
  $contents['custom_text'] = array(
    'info' => t('Custom text'),
    'group' => t('Text'),
  );

  // Custom heading
  $contents['custom_heading'] = array(
    'info' => t('Custom heading'),
    'group' => t('Text'),
    'no_title' => TRUE,
  );
  // Insert image
  $contents['image'] = array(
    'info' => t('Insert an image'),
    'group' => t('Image'),
  );

  $contents['youtube'] = array(
    'info' => t('Youtube'),
    'group' => t('Video'),
  );
  $contents['vimeo'] = array(
    'info' => t('Vimeo'),
    'group' => t('Video'),
  );

  $contents['icon'] = array(
    'info' => t('Icon'),
    'group' => t('Icon'),
  );
  return $contents;
}

```

I can rewrite them in my own function, but I have no idea how to remove them. I thought through `$contents['custom_text']` but I'm not sure. Of course, I can remove the original code, but I do not like it.

It looks like `unset($contents['custom_text'])` is working, but can I run this from another file/function?

**EDIT**

```
/**
 * Implements HOOK_builder_content_info_alter()
 */
function builder_gc_builder_content_info_alter(&$contents) {
    unset($contents['node']);
}

```

# Answer
> 3 votes
The function you are showing is an implementation of `hook_builder_content_info()`. Without seeing the code that calls that hook, I cannot answer about removing the vertical tabs, but I can just give some hints.

If the module also invokes `hook_builder_content_info_alter()`, which is normally done from the majority of the Drupal modules using hooks, you can implement `hook_builder_content_info_alter()` in a module.

```
/**
 * Implements hook_builder_content_info_alter()
 */
function builder_gc_builder_content_info_alter(&$contents) {
  unset($contents['node']['group']);
}

```

The alter hook could get other arguments, but the structure to change is always the first.

If the module doesn't invoke any `hook_builder_content_info_alter()` you need to:

* Avoid Drupal invokes `builder_builder_content_info()`
* Implement `hook_builder_content_info()` using the same code used by `builder_builder_content_info()` but without those parts that you don't want

This can be done with the following code.

```
function builder_gc_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'builder_content_info') {
    // Remove the implementation done from that module.
    unset($implementations['builder']);
  }
}

function builder_gc_builder_content_info() {
  $blocks = _block_rehash();
  $contents = array();
  if (!empty($blocks)) {
    foreach ($blocks as $key => $block) {
      $contents[$block['delta']] = array(
        'info' => $block['info'],
        'type' => 'block',
        'group' => t('Block'),
        // This is name of group to collect contents in a tab
        'block_module' => $block['module'],
      );
    }
  }

  // node add content
  $contents['node'] = array(
    'info' => t('Adding existing node'),
  );

  //Custom text
  $contents['custom_text'] = array(
    'info' => t('Custom text'),
    'group' => t('Text'),
  );

  // Custom heading
  $contents['custom_heading'] = array(
    'info' => t('Custom heading'),
    'group' => t('Text'),
    'no_title' => TRUE,
  );
  // Insert image
  $contents['image'] = array(
    'info' => t('Insert an image'),
    'group' => t('Image'),
  );

  $contents['youtube'] = array(
    'info' => t('Youtube'),
    'group' => t('Video'),
  );
  $contents['vimeo'] = array(
    'info' => t('Vimeo'),
    'group' => t('Video'),
  );

  $contents['icon'] = array(
    'info' => t('Icon'),
    'group' => t('Icon'),
  );
  return $contents;
}

```

The code I am showing should avoid the information is shown in vertical tabs, but it doesn't avoid the vertical tabs are created. The only way to be sure is to alter the function that invokes `hook_builder_content_info()`. Using `hook_builder_content_info_alter()`, you are sure to alter the value returned from all the `hook_builder_content_info()` implementations, while the other snippet I shown just alters the value returned from a module. If there are two modules passing `'node'` as group, the vertical tab will be created, since I am not altering what returned from the other module.

Also, the code I am showing removes the `'group'` property, which I am guessing sets the vertical tab where the information is shown, similarly to the #group property used by fieldsets.

Alternatively, you can use the following code, which removes completely the information about the part you don't want to see.

```
// Case 1.

/**
 * Implements hook_builder_content_info_alter()
 */
function builder_gc_builder_content_info_alter(&$contents) {
  unset($contents['node']);
}

```

```
// Case 2.

function builder_gc_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'builder_content_info') {
    // Remove the implementation done from that module.
    unset($implementations['builder']);
  }
}

function builder_gc_builder_content_info() {
  $blocks = _block_rehash();
  $contents = array();
  if (!empty($blocks)) {
    foreach ($blocks as $key => $block) {
      $contents[$block['delta']] = array(
        'info' => $block['info'],
        'type' => 'block',
        'group' => t('Block'),
        // This is name of group to collect contents in a tab
        'block_module' => $block['module'],
      );
    }
  }

  //Custom text
  $contents['custom_text'] = array(
    'info' => t('Custom text'),
    'group' => t('Text'),
  );

  // Custom heading
  $contents['custom_heading'] = array(
    'info' => t('Custom heading'),
    'group' => t('Text'),
    'no_title' => TRUE,
  );
  // Insert image
  $contents['image'] = array(
    'info' => t('Insert an image'),
    'group' => t('Image'),
  );

  $contents['youtube'] = array(
    'info' => t('Youtube'),
    'group' => t('Video'),
  );
  $contents['vimeo'] = array(
    'info' => t('Vimeo'),
    'group' => t('Video'),
  );

  $contents['icon'] = array(
    'info' => t('Icon'),
    'group' => t('Icon'),
  );
  return $contents;
}

```

If this code doesn't work, you could follow the following steps, in order to change the module behavior:

* Check which function is invoking `hook_builder_content_info()`
* Verify if there is a reference to that function in one of the hooks Drupal uses (e.g. `hook_menu()`); the reference could be either direct or indirect (i.e., the reference is for a function that calls the function invoking `hook_builder_content_info()`)
* If this is the case, using the alter hook Drupal uses (e.g. `hook_menu_alter()`), you can change that reference with a reference to a function you write, which uses the code the original function uses, without the part you don't want.

In this way, you aren't directly altering the values returned from `hook_builder_content_info()`, and you need to copy more of the code used from the module for which you are altering the behavior; this is also means that, for every minimal change in the module you bought, you need to check your code to be sure it doesn't alter the expected behaviour.

---
Tags: 7, hooks
---


# Question
Title: Can we migrate basic Metatag data without customization?
I'm ought to Migrate-upgrade from D7 to D8 and deleted **all** modules besides Metatag (and its dependencies --\> Ctools and Token).

You might have an idea how could I keep all the basic Metatag data for my nodes? By "basic" I mean only to the Page-title, Page-description and Meta keywords (And maybe also the Abstract tag); Nothing beyond that.

AFAIK, as for 2016 there is no migration-path for the Metatag module and people should generally copy their metadata manually; This situation kind of negates the whole migration experience since the all issue is to migrate nodes with their most common data.

Will cherish any advice.

# Answer
> 2 votes
There's a patch at https://www.drupal.org/node/2563649, currently at "Needs work".

---
Tags: migrations, upgrading, meta-tags
---


# Question
Title: subject and body of mail messages empty using drupal 8 mail api - hook_mail
I'm trying to send messages using Drupal 8's Mail API, but the messages always have an empty subject and body. Do you see anything wrong with the code?

In my module file:

```
function mymodule_mail($key, &$message, $params) {
    $options = array(
        'langcode' => 'en'
    );

    switch ($key) {
      case 'contact':
        $from = \Drupal::config('system.site')->get('mail');  //I'm not sure this is actually doing anything.
        $message['subject'] = 'Inquiry from Web Site';
        $message['body'][] = 'TEST BODY';
        break;
}

```

And within the submit method of my form:

```
 $langcode = 'en';
 $to = 'my@email.com';

 $mailManager = \Drupal::service('plugin.manager.mail');
 $module = 'mymodule';
 $key = 'contact';

 $send = true;
 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

```

I am getting the messages - and they are coming from the right email address (which may just be the default). But the subject and body are empty and I can't figure out why. Any suggestions would be appreciated!

# Answer
> 1 votes
Ok, I found the problem. You're gonna laugh!

My code for hook\_mail was within the code block for the function above it! D'oh! All good now. Sorry for the false alarm.

---
Tags: emails
---


title: Multiplied db_results when multiple IN

text:
# Question
Title: Multiplied db_results when multiple IN
I am stuck since yesterday on a problem that is making me crazy, I feel like I am missing something. Here is the context: I am products (a node). In each products, I have tags (taxonomy terms), in a term reference field with an unlimited values possible.

I am simply trying to query my items, using a tag filter. But as soon as I select multiple tags, if the multiple as those tags, results is multiply by the number of corresponding tags.

The query is pretty big so I am simplifying it here to achieve the same result.

**Node structure:**

```
Title ------- | Quantity | Tags Tid
Product 1 --- | -- 1 --- | 12, 15
Product 2 --- | -- 4 --- | 13

```

**Tables looks like this:**

Node:

```
Title ------- | Nid
Product 1 --- | 320
Product 2 --- | 321

```

Quantity:

```
quantity_value | entity_id
1 ------------ | 320
4 ------------ | 321

```

Tags:

```
tid | entity_id
12  | 320
13  | 321
15  | 320

```

I am using db\_query for my query:

So let's say that I want to filter on product that has Tags tids equal to 12 and 15 (product 1)

```
$query = db_query("
  SELECT n.title, SUM(q.quantity_value)
  FROM {node} n
  JOIN {quantity} q
  ON q.entity_id = n.nid
  LEFT JOIN {tags} t
  ON t.entity_id = n.nid
  WHERE t.tid IN (12, 15)
  GROUP BY n.title
  HAVING COUNT(DISTINCT t.tid) = count(12,15)
");
$results = $query->fetchAll();

```

That query returns me 1 row, with product 1, but quantity = 2, instead of 1. I have tried sub querying the "IN" and multiple other stuff, but nothing has worked. The only solution I have now is to divide SUM(q.quantity\_value) by COUNT(n.title), it would work, but I think there is better way to do it :)

Thanks for your help!

Ed

# Answer
Hum... Classic "I am sure I tried that before and it wasn't working"... I spent an entire day looking for the solution, and find it 5 minutes after posting here :)

```
$query = db_query("
  SELECT n.title, SUM(q.quantity_value)
  FROM {node} n
  JOIN {quantity} q
  ON q.entity_id = n.nid
  WHERE EXISTS (SELECT *
    FROM {tags} t
    WHERE t.entity_id = n.nid
    AND t.tid IN (12, 15))
    HAVING COUNT(DISTINCT t.tid) = count(12,15)
  GROUP BY n.title
");
$results = $query->fetchAll();

```

Subquery was the way to go (if anyone has something better to suggest, I would love to hear it).

Thanks,

Ed
> 0 votes

---
Tags: 7, database
---


title: Load title and header HTML by URL

text:
# Question
Title: Load title and header HTML by URL
I'm using drupal 7 and I want to load the view title and header HTML of this view by Its URL. Is IT possible?

# Answer
> 2 votes
There's not a direct function that I'm aware of. But you can query the `views_display` DB table, indirectly to retrieve your view as the path data is serialized information:

```
function get_view_from_path($path) {
  $page_views = db_select('views_display','vd');
  $page_views->join('views_view', 'vv', 'vv.vid = vd.vid');
  $page_views = $page_views->fields('vd')
    ->fields('vv')
    ->condition('display_plugin', 'page')
    ->execute();

  foreach ($page_views as $view) {
    $options = unserialize($view->display_options);
    if ($options['path'] == $path) {
      return views_get_view($view->name);
    }
  }
  return FALSE;
}

if ($my_view = get_view_from_path('my-view-path')) {
  // @TODO: Look @ $my_view->display["page"]->display_title
  // $my_view->display["page"]->display_options['header']
  // for title & header data.
}

```

---
Tags: 7, views
---


title: How to create custom form and theme?

text:
# Question
Title: How to create custom form and theme?
I am new to drupal and this community. I want to create a form like below.

I write my custom form but my question is how can I show my form table format like columns and rows headers?

There can be already asked question for this too.Can anyone provide me some links or give me some hints.I am using drupal 7.

Thank You.

# Answer
> 1 votes
This is more of a hint since I don't have "comment" privileges yet. You could create 4 field sets to accommodate the rows. Then create the collected funds and donor fields and when you add fields in each field set, use the respective field rather than create new ones.

So you are then left with html that you can very easily manipulate into having the appearance of being a table.

You would need to position the fieldset label to the left rather than on top and then hide the field labels for all but the first field set (giving it an absolute position and setting the first field to have enough left margin should accommodate this.

Then position the fields by either setting max widths and floating left to keep it responsive or setting the width of the field and the fieldset so that it's not responsive.

---
Tags: theming, webforms
---


# Question
Title: How to send email when customer cancel payment?
I am using Drupal Commerce 7x-1.10 and PayPal WPS 7.x-2.3 module. How can I send an email to customer (both anonymous and authenticate), if they cancel the order or cancel the payment method or cancel anytime within the checkout process?

I am using rules, also I have use "cancelled" in the Condition section. But for some reason it is not working. Please see below for the rules code -

```
{ "rules_completing_the_checkout" : {
    "LABEL" : "Completing the checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:status" ], "value" : "canceled" } }
    ],
    "DO" : [
      { "mimemail" : {
          "key" : [ "commerce-order:mail" ],
          "to" : [ "commerce-order:mail" ],
          "cc" : [ "" ],
          "subject" : "Cancel Order? Why",
          "body" : "Cancel Order? Why",
          "plaintext" : "Cancel Order? Why",
          "language" : [ "commerce-order:state" ]
        }
      }
    ]
  }
}

```

# Answer
I think you can implement it via the module Rules

Just add the action "Send email" for a custom rule that has the "order state changes" event conditionally on order state "cancelled."
> 2 votes

# Answer
Did you found any solution to this? If not, here's what you can do....

1. Create a module with custom event `hook_rules_event_info`
2. Implement `hook_redirect_form_back` and `hook_process_callback` in your payment gateway
3. Use `rules_invoke_event` in your above method to execute the rule.
4. Use Rules UI to create new rule with the above event and send mail as action.

Example:

```
/**
 * Implementation of hook_rules_event_info()
 */
function YOURMODULE_rules_event_info() {
    return array(
        'commerce_payment_canceled_event' => array(
            'label' => t('Commerce payment canceled'),
            'module' => 'YOURMODULE',
            'group' => 'Any group' ,
            'variables' => array(
                'commerce_order' => array(
                    'type' => 'commerce_order',
                    'label' => t('Completed order', array(), array('context' => 'a drupal commerce order')),
                ),
            ),
        ),
    );
}

    /**
     * + * Payment method callback: redirect form back callback.
     * + */
    function PAYMENTGATEWAY_redirect_form_back($order, $payment_method)
    {
        // Display a message indicating the customer canceled payment.
        //Can also be done in rule via set system message and level set to error
        drupal_set_message(t('You have canceled payment but may resume the checkout process here when you are ready.'), 'error');

        // If you wish to reset selected payment while redirecting
        unset($order->data['payment_method']);

        // Process callback information from gateway.
        return PAYMENTGATEWAY_process_callback($order, $payment_method);
    }

    function PAYMENTGATEWAY_process_callback($order, $payment_method)
    {
        rules_invoke_event('commerce_payment_canceled_event', $order);

    }

```

Found this base idea from someone using Ogone payment gateway.
> 1 votes

---
Tags: commerce, rules, emails
---


title: minihtml is not compress output

text:
# Question
Title: minihtml is not compress output
I am using the Minify HTML module to compress the HTML output. Once, I enable this module and view my node page, the HTML is not compressed. Is there any additional setting for this?

# Answer
Remember what this module does is:

**This module removes all the whitespace in your HTML except those between TAGS.**

It will not compress all your HTML into one single line.
> 1 votes

---
Tags: performance
---


# Question
Title: PDO expecption error while adding class to the block with sql server
> "PDOException: SQLSTATE\[42S22\]: \[Microsoft\]\[ODBC Driver 11 for SQL Server\]\[SQL Server\]Invalid column name 'css\_class'.: UPDATE block SET \[css\_class\]=:db\_update\_placeholder\_0 WHERE (\[module\] = :db\_condition\_placeholder\_0) AND (\[delta\] = :db\_condition\_placeholder\_1) ; Array ( ) in block\_class\_form\_submit() (line 99 of .....\sites\all\modules\block\_class\block\_class.module)."

Adding class to the block using block class module. while adding class to the block throwing pdo exception error coming. Please any one resolve problem.

# Answer
> 0 votes
Instead of install one module for this, you can just use the ID for that block and create your custom css.

Example:

```
div#block-block-10{
    background-color: blue;
}

```

I think that could solve your problem

---
Tags: blocks
---


# Question
Title: how theme/template connected/related to each other
for example, I have:

1. module id: `module_id` (file: `module_id.info.yml`)
2. FieldType ID: `FieldTypeID` (file: /src/plugin/Field/FieldType/`FieldType.php`)
3. FieldWidget: `FieldDefaultWidget` (file: /src/plugin/Field/FieldWidget/`FieldDefaultWidget`.php)
4. FieldFormatter: `FieldDefaultFormatter` (file: /src/plugin/Field/FieldWidget/`FieldDefaultFormatter`.php)

and inside my field formatter:

```
public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#theme' => 'my_field',
        '#type' => 'markup',
        // etc...
      ];
    }

    return $elements;
  }

```
5. I have file: `my_field`.module

with function:

```
function my_field_theme() {
  return array(
    'location_field' => array(
      'variables' => array(
        'x' => NULL,
        'y' => NULL,
        'z' => NULL,
      ),
      'template' => 'my_field',
    ),
  );
}

```
6. and I have template file: /templates/`my_field`.html.twig

as simple as:

```
<section class="class">
  <h2>name</h2>
  <div class="cls" data-x="x" data-y="y" data-z="z">content</div>
</section>

```

with that, seems like i can't see my template, which i don't have any idea why?

how is theme or template name relate with the filename (or ID or anything)? - how are they connected each other?

what is the rule for that?

Thank you,

AnD

# Answer
> 1 votes
If your code is only in one module with the name module\_id, then in 5. the file should be named `module_id.module` and the function `module_id_theme()`

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


# Question
Title: Views conditional fileds: multiple values
I have a content type with the following field:

List (float) - blue - green - yellow

In the view, I want a condition that says that if the value is "blue" display this: div class="blue"

If it is green display class="green"

If it is empty display class ="empty"

And so on...

I tried Views Conditional Module but it can't handle multiple values...

What is the best way to do this?

# Answer
> 2 votes
I solved this with a simple solution:

Added custom text field in views and something like: div class="\[field\_value\]"

The result of the field (blue,green,empty) is the class of the div so I can manipulate the css.

Thank you

# Answer
> 0 votes
You can have a look at the module https://www.drupal.org/project/js\_injector by which you can add JS snippet in the header or footer of a page.

---
Tags: views, entities
---


title: Facet pretty path providing no result

text:
# Question
Title: Facet pretty path providing no result
I have used commerce kickstart and created product display page with facet filter.I have used **Facet API Pretty Paths module** to use simple URL.But it makes no result behaviour.Without facet pretty path, facet filter working good, but URL makes quite complex.

# Answer
> 0 votes
Unfortunately this is a bug in Facet API Pretty Paths module. take a look at https://www.drupal.org/node/2423029 and ask maintainer to solve or suggest a solution for it.

---
Tags: commerce, search
---


# Question
Title: View that display single node which has id the same as last part of url (from last / to the end)
I have an urls:

* website.com/portfolio-entries/23
* website.com/portfolio-entries/25

I would like to make an view for them to display node which has id the same as last part of url (from last `/` to the end).

I have red the description for View \> Url (administration panel \> Content \> Views \> My\_view):

> This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy\_term

So I set it to `portfolio-entries/%entry_id` (I hope I understood it right).

But how now make this view display only sinlge entry which has the id set to `%entry_id`?

I've tried with View \> Filters (add) \> ID but I can only set there hard-coded values (e.g. 23 makes this view display only entry #23). How can I place there my `%entry_id`?

In other words I was reproducing steps from https://www.ostraining.com/blog/drupal/views-specific-node/ (it's for Drupal 7 but it works the same way in Drupal 8) **but instead of har-coding the id value I want to take it from last part of the url.**

# Answer
> 0 votes
Normally the parameter is not named, it is a single % without name:

```
portfolio-entries/%

```

The example `node/%/feed` is also a single % in the middle part of the url. The third part of the url is a fixed `feed`, so that only urls with a `/feed` at the end will match.

To use this parameter for filtering you need to set a contextual filter in the advanced settings. If you only have one parameter, this filter will automatically get this, when selecting the field you want to filter.

---
Tags: views, theming, uri
---