# Question
Title: How to make sure that /taxonomy/term/24/WHATEVER gives 404?
Google found up some weird links on my website and has started indexing stuff like `/taxonomy/term/24/WHATEVER`. I don't want that.

I also don't want to find all these URLs manually, ideally they will turn up in Google Webmaster's list of broken links and I can fix them using that list.

Unfortunately in the taxonomy term view at PAGE SETTINGS it just says `Path: /taxonomy/term/%`. Is there a good way to respond 404 on `/taxonomy/term/24/WHATEVER` addresses?

# Answer
> 1 votes
You can try Rabbit Hole module.

From its page:

> Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
>
> This works by providing multiple options to control what should happen when the entity is being viewed at its own page. You have the ability to
>
> * Deliver an access denied page.
> * ***Deliver a page not found page***.
> * Issue a page redirect to any path or external url.
> * Or simply display the entity (regular behavior).
>
> **Supported entities**
>
> The currently supported entities are:
>
> * Nodes
> * ***Taxonomy terms***
> * Users
> * Files

# Answer
> 1 votes
I've done something similar, but there might be some edge cases where this solution might not be suitable.

You can use hook\_taxonomy\_term\_view() and within that check if the amount of arguments in the URL (`$_GET['q']`) is more than three.

```
/**
 * Implements hook_taxonomy_term_view().
 */
function custom_module_taxonomy_term_view($term, $view_mode, $langcode) {
  if (count(arg()) > 3) {
    // This will throw a 404.
    drupal_not_found();
  }
}

```

---
Tags: 7, views, taxonomy-terms, uri
---


# Question
Title: Is there a Rules Condition for 'is user:' or 'is root user'?
I am creating a rule that will help to manage permissions, but I only want it to run for the user with `uid=1`.

Is there a way to add a Rules Condition based on user data? Is such a condition prone to problems, and should I instead need to create a new permission?

# Answer
Sure there is such Rules Condition. As an example, have a look at the Rule I included in my answer to "How to stop a Views block from displaying to admins, such as user/1?".

The Rules Condition included that answer performs a Data Comparison to check if the value of `site:current-user:uid` is not equal to `1` (in your case you'd want to check if it is equal to `1`).

**Note**: This specific Rules Condition comes in handy for anything you want to enforce (or prohibit?) for super user user/1 (which typically skips all permissions), similar to what the question was about in the linked question here.
> 1 votes

---
Tags: 7, users, rules
---


# Question
Title: How to change or influence the block id and class of a view block
I have a view with 2 blocks. One was cloned from the other. I changed the machine readable name of both of the blocks (`block_events_upcoming` and `block_events_upcoming_ical`), but in the html i get as id and classes the beautys you see below.

```
<div id="block-views-d7410a6d5618e2d319a0eaab549b0ff2"
     class="block block--views
            contextual-links-region
            block--views-d7410a6d5618e2d319a0eaab549b0ff2">

```

Is there a way to change the ids and classes of the block. The css-class option in advanced settings only changes the css class in the block\_content div not the top block-div.

# Answer
> 2 votes
The HTML ID is generated by concatenating block-view\_name-block\_name and it seems there's a length limit of 32 characters. My block exceeded that limit. So for me the solution was to shorten the block-machine-name.

# Answer
> 0 votes
Have you tried to give your blocks an id through the 'advanced' fieldset of your view? on the 'other' list of settings. That might do the trick.

---
Tags: views
---


title: Move template function to custom module

text:
# Question
Title: Move template function to custom module
I have a function in my template.php file but I've now created a module that manages these particular tasks so I want to move the function over.

This is what I have in my template.php file:

```
function MYTHEME_menu_tree__main_menu($variables){
    return '<ul class="menu my-class">' . $variables['tree'] . '</ul>';
}

```

This works file but when I move it into my custom module (`mymodule.module` file) if doesn't work.

I've tried this:

```
function MYMODULE_menu_tree__main_menu($variables){
    return '<ul class="menu my-class">' . $variables['tree'] . '</ul>';
}

```

and this:

```
function MYMODULE_preprocess_menu_tree__main_menu($variables){
    return '<ul class="menu my-class">' . $variables['tree'] . '</ul>';
}

```

but not happening.

Can anyone see where i'm going wrong? or am I way off on this and it can't be done like this?

# Answer
> 0 votes
`hook_theme_registry_alter()` allows a module to step in to override registered theme callback functions. In your case, you're looking to override the `menu_tree__main_menu` entry and replace its callback function:

```
/**
 * Implements hook_theme_registry_alter().
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  if ($theme_registry['menu_tree__main_menu']) {
    // @TODO: override
    // $theme_registry['menu_tree__main_menu']['function']
    // $theme_registry['menu_tree__main_menu']['type']
    // $theme_registry['menu_tree__main_menu']['theme path']
    // for your new module theme function
  }
}

```

See the **Return Value** section of `hook_theme()` for more information on what a theme registry entry contains.

---
Tags: 7, theming
---


# Question
Title: Access denied on hello world custom module
I installed Drupal 8 on a Debian VPS server. Some installed themes don't work; some themes do work.

After I created a simple *Hello World* module and tried to access its page, I got an *Access denied* error.

These are the files I created for the module.

### hello\_world.info.yml

name: Hello World
type: module
description: 'A basic Drupal 8 Hello World Module.'
package: Custom Modules
version: 1.0
core: 8.x

### hello_world.routing.yml

```yaml
hello_world_settings:
  path: '/hello/world'
defaults:
  _controller: '\Drupal\hello_world\Controller\HelloWorldController::
myCallbackMethod'
  _title: 'Hello World'
requirements:
  _permission: 'access content'
</code></pre>

### hello\_world/src/Controller/HelloWorldController.php

```
/**
* @file
* Contains \Drupal\hello_world\HelloWorldController.
*/
namespace Drupal\hello_world\Controller;
/**
 * Provides route responses for the hello world page example.
 */
class HelloWorldController {
  /**
  * Returns a simple hello world page.
  *
  * @return array
  * A very simple renderable array is returned.
  */
  public function myCallbackMethod() {
    $element = array(
      '#markup' => '
Saying Hello World in Drupal 8 is cool!
',
    );
    return $element;
  }
}

```

Can anyone please explain what is going on?

# Answer
The issue is with the indentation of the `hello_world.routing.yml` file. Simply change the indentation of it to:

```
hello_world_settings:
  path: '/hello/world'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloWorldController::myCallbackMethod'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

```

And the *Access denied* issue should be solved. The indentation of YAML file is important, in Drupal 8. It should be as follow:

* `path`, `defaults`, and `requirements` should be indented by 2 spaces
* `_controller`, `_title`, and `_permission` should be indented by 4 spaces
> 10 votes

---
Tags: 8, routes, users
---


# Question
Title: How do I get a paginated view to display rel="next/previous" tags?
Using Drupal 7.

I've got several views (most of which listing articles which have been posted) that paginate and I'd like to add;

```
<link rel="prev" href="http://example.com/recent-articles?page=0" />
<link rel="next" href="http://example.com/recent-articles?page=2" />

```

links to them.

How do I do this? A module is preferred, changing the `php` files would preferably be avoided.

Things I've tried:

# Answer
> 0 votes
You just need to override `theme_pager_previous()` and `theme_pager_next()` (easiest to do in your theme):

```
function MYTHEME_pager_previous($vars) {
  $text = $variables['text'];
  $element = $variables['element'];
  $interval = $variables['interval'];
  $parameters = $variables['parameters'];
  global $pager_page_array;
  $output = '';

  // If we are anywhere but the first page
  if ($pager_page_array[$element] > 0) {
    $page_new = pager_load_array($pager_page_array[$element] - $interval, $element, $pager_page_array);

    // Changes from core function start here.
    $attributes = array('rel' => 'prev');

    // If the previous page is the first page, mark the link as such.
    if ($page_new[$element] == 0) {
      $output = theme('pager_first', array('text' => $text, 'element' => $element, 'parameters' => $parameters, 'attributes' => $attributes));
    }
    // The previous page is not the first page.
    else {
      $output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters, 'attributes' => $attributes));
    }
  }

  return $output;
}

```

And the same thing for pager\_next.

# Answer
> 0 votes
It seems like there is a contrib module outside of D.O. that does the trick.

https://github.com/nlisgo/nextprev\_links

Have you already tried this one?

# Answer
> 0 votes
I had the similar issue of combining multiple views and give the pager so they all combined, and can accessible by the pager. I have asked previously on DA and here is the link just see the detail of answer and question you will automatically will get idea how you can do it.

How to add pager at the bottom which allow shifting between views?

Basically, you can do by this views, all your articles in one views and add new display page and go increasing offset +1 in pager for subsequent pages. Just follow the answer you will get idea. And lastly add the pager as described in the answer to combine all.

---
Tags: views, uri
---


# Question
Title: How to set the visibility rule for pane to not show up when any user is logged in?
I have created three panes (as shown below) using **Mini Panel module**. as named below,

`Login/Register | Username | Logout`

This I want to keep at the top left of website. Now, how each pane is created

1. `Login/Register`: Created menu and added link named `Login/Register` and have given the path `/user`. So, it leads to login page.
2. `Username`: This I created using the `Views`, a block created of users and filter was given that the user is `logged in`. hence it will automatically show up only when the user is logged in.
3. `Logout`: This I created using menu, with name `Logout` and path `user/logout`, hence when it gets clicked the user gets logout and this pane disappears automatically.
4. When users are logged-in, only the *Username and Logout* pane should appear; hence, users can see their profile by clicking on their name, or they can log out. When users log out, this pane disappears.
5. When user are not logged-in, only the *Login/Register* pane should appear.

So, the *Username and Logout* pane works perfectly fine.

What SELECTION rule shall I give to the *Login/Register* pane, so it gets visible only to anonymous users?

# Answer
While adding a Visibility rule to the pane, select **User:Role** and then select **"anonymous"**. This way the pane will be shown only to anonymous (not logged in) users.
> 2 votes

---
Tags: panels
---


title: Consume nodes from REST export views

text:
# Question
Title: Consume nodes from REST export views
I am trying to import nodes from a different domain's REST export view. I am able to get all serialized nodes from the view through Guzzle but once I try to create a node from the hal+json response I get this error:

```
Type http://drupaltest.dev/rest/type/node/article does not correspond to an entity on this site

```

This is the code I'm using to create the node:

```
$data = $request->getBody();
$output = \Drupal::service('serializer')->decode($data, true);

$entity = \Drupal::service('serializer')->denormalize($output[5], Node::class, 'hal_json');

```

Any ideas how to create the node? Using only json instead hal+json works but does not give me the entity relationships.

---

**EDIT 1**

Alright, so it seems I needed to replace all references to the source site with the receiving website. But the denormalization step does not create entities referenced by the selected node (I'm most interested references to images). Any suggestions?

# Answer
> -1 votes
You need to set your rest permissions for articles/nodes such that the user you are using can create and view them. I'll update this answer with paths when I'm back at a computer.

---
Tags: nodes, files, importing-exporting, 8
---


# Question
Title: Requiring a package doesn't find a dependency
When running `HOME=/home/gymsagec composer require "drupal/commerce 8.2.x-dev"`, I get this error message:

> drupal/commerce 8.2.x-dev requires commerceguys/intl dev-master -\> no matching package found

I can install the intl package by itself using composer but even after doing that, running the first script fails. Why?

# Answer
> 0 votes
As reported in Composer fails when installing a dependency of a dependency, but not when the dependency is installed directly. that probably happens because the root composer.json file doesn't set a minimum stability, or doesn't accept a less stable package.

Try with `composer require drupal/commerce:@dev` as suggested in that issue report.

---
Tags: commerce, composer
---


# Question
Title: Installing on IIS 7/Windows Server 2008 R2/MSSQL 2008
I am having difficulty connecting to my MSSQL database (locally installed) while proceeding through the Drupal Install. I do not get any errors during the Verify Requirements portion, but not matter what info I put into the Database configuration page, it cannot connect. It does not throw an error like "phpmssql library missing"

This is what I have installed so far.

* Windows 2008 Server R2
* Internet Information Server IIS 7.5
* SQL Server 10.0
* Microsoft Drivers for PHP for SQL Server 3.2
* php-5.6.21-nts-Win32-VC11-x86
* php\_pdo\_sql\_srv\_56\_nts.dll
* php\_wincache-1.3.7.9-5.6-nts-vc11-x86
* sqlsrv-8.x-1.x-dev
* wincachedrupal-7.x-1.10

Should I be putting something besides "localhost" and "1433" in the "Advanced Options" panel?

Thanks in advance for any help!

# Answer
> phpmssql library missing

You are using the 8.x-2.x branch of the driver, that relies on a paid external library phpmssl:

http://www.drupalonwindows.com/en/content/phpmssql

You can use the "free" 8.x-1.x branch - that has no dependencies - for evaluation purposes. I say evaluation because it's a non supported half-broken branch I used to work on during the first D8 port attempt of the driver.

You can find full discussiones of this issue here:

http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows

Disclaimer: I'm the maintainer for the SQL Server driver, PHP Mssql and Wincache.
> -1 votes

---
Tags: 8, iis
---


title: override MenuLinkTree Block

text:
# Question
Title: override MenuLinkTree Block
I want to override the block menu behavior, but i don't know how to do that, because the menu block are created dynamically.

I know add some block with the block plugin, like this :

```
/**
 *
 * @Block(
 *   id = "system_name_block",
 *   admin_label = @Translation("my Block"),
 * )
 */

```

But i don't find how the core deal to create dynamic block for the Menu link tree.

I ever know that i have to override this class to get the espected behavior : Drupal/Menu/MenuLinkTree.

But Now i've to know how to create dynamically some block to use it.

# Answer
The menu block is defined in the core module `system`.

Here you can see how the menu tree is set when creating the object:

```
core/modules/system/src/Plugin/Block/SystemMenuBlockTest.php:

namespace Drupal\system\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Menu\MenuActiveTrailInterface;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a generic Menu block.
 *
 * @Block(
 *   id = "system_menu_block",
 *   admin_label = @Translation("Menu"),
 *   category = @Translation("Menus"),
 *   deriver = "Drupal\system\Plugin\Derivative\SystemMenuBlock"
 * )
 */
class SystemMenuBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The menu link tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuTree;
  ...
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MenuLinkTreeInterface $menu_tree, MenuActiveTrailInterface $menu_active_trail) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->menuTree = $menu_tree;
    $this->menuActiveTrail = $menu_active_trail;
  }

```

How to use your own menu tree in a menu block you can see in this test:

```
core/modules/system/src/Tests/Block/SystemMenuBlockTest.php

```

Example from SystemMenuBlockTest.php. A menu that was created before is put in a block config:

```
$block = Block::create(array(
      'plugin' => 'system_menu_block:' . $this->menu->id(),
      'region' => 'footer',
      'id' => 'machinename',
      'theme' => 'stark',
    ));

```
> 0 votes

---
Tags: 8, blocks
---


# Question
Title: Testing an update hook that updates fields?
I wrote an update hook for a site that moves data from one field to another. It looks a lot like this gist:

```
  foreach ($node_ids as $node_id) {
    try {
      $node_wrapper = entity_metadata_wrapper('node', $node_id);
      $node_wrapper->field_new_field->set($node_wrapper->field_old_field[0]->value());
      $node_wrapper->save();
    }
    catch (Exception $e) {
      watchdog('mymodule', 'Problem with node @node_id', array('@node_id' => $node_id), WATCHDOG_ERROR);
    }
    $sandbox['progress']++;
  }

```

It's being tested on CI (Travis) which runs "drush updatedb -y" so what I was wondering is if there is a way to query a particular node and make sure the field is populated? Like for example make sure the data in field\_new\_field is the same as \_field\_old\_field and printing that on the command line?

# Answer
> 3 votes
Yes, very quickly. You already have part of the code. Since you have already loaded the node via the entity\_metadata\_wrapper() you have all of the information at your finger tips.

An example is this in your hook\_update\_N()

```
foreach ($node_ids as $node_id) {
    try {
      $node_wrapper = entity_metadata_wrapper('node', $node_id);
      $node_wrapper->field_new_field->set($node_wrapper->field_old_field[0]->value());
      $node_wrapper->save();
      if ($node_wrapper->field_new_field->value() == $node_wrapper->field_old_field->value()){
        print_r('Success. Old field data is in new field data');
      }
    }
    catch (Exception $e) {
      watchdog('mymodule', 'Problem with node @node_id', array('@node_id' => $node_id), WATCHDOG_ERROR);
    }
    $sandbox['progress']++;
  }

```

I added a comparison of the old field data and the new field data. If it is the same, it will print 'Success. Old field data is in new field data' in the console of Travis-CI. You can do this for any entity. You can use print\_r() to output data that you can see in Travis-CI's console. I do this for troubleshooting my test scripts when I may be using a new test method I have never used before and I want to see what Drupal is giving me. Most of the modules I maintain on D.O are tested with Travis-CI.

---
Tags: testing, updating
---


# Question
Title: How to create a Privatemsg thread with multiple recipients in a Rules component?
I'd like to send private messages to a selected group of users. For this purpose I use a view with VBO and a Rules component action (utilizing the "Send message" action provided by Privatemsg) - as described in this question.

However, I still have a minor issue with it: Since I send the messages looping through the list of users, privatemsg module sends individual messages and doesn't create a thread with multiple users. Is it possible to use the whole array of users in a single "Send message" action?

Probably one solution might be to use cutoms PHP code in rules component and create thred with privatemsg\_new\_thread function. But it's not a very drupalish way, I guess.

# Answer
I found a solution using a rule component with custom php code. It needs some changes in privatmsg module, see in this discussion: https://www.drupal.org/node/2725325
> 0 votes

---
Tags: 7, rules, privatemsg, actions
---


# Question
Title: Displaying fields in entity_reference data
I'm using the entityreference module to provide my "Concert" content type with a "Program" field (machine name "field\_program"), containing multiple "Song" nodes. Each Song just has two fields: Title and Composer (machine names "title" and "field\_composer").

What's the best way to control the display of a Program field within a Concert node? I tried creating a "node--field\_program.tpl.php" file, but that didn't seem to have an effect. I also created a View that lists Song nodes in basically the way I'd want, but I don't know how to use that in the context of displaying a Concert node.

# Answer
I'd recommend replacing program field with a custom View of Songs. That will allow you to pull any data that you'd need from the Song content type.

The least cumbersome (and I'd say flexible) way of doing involves two steps:

1. **Create a View of Songs** that will take a Node ID (NID as a contextual filter)
2. **Override the field template for the Program field** and instead of rendering the default template of the field - render a View crated in Step 1.

I'll detail each step, creating a View for this purpose can be somewhat complex, but that will give you great control over how you want to present the information.

**STEP 1 - CREATE A VIEW**

1. Create new View of "`Content`" of the type "`Concert`". Select Block instead of Page. Make it a view of "`Unformatted List`" of "`Fields`". In the number of items put `0` to display all items.
2. Add new "`Contextual Filter`" - "`Content: NID`". Provide default value: "`content ID from URL`"
3. Add new Relationship to "`Entity Reference: field_program`", which will give you a connection to each song selected in the filed Program for the particular node. Make relationship required.
4. Now remove all default fields that were placed in your View and add fields from the Songs content type (Title and Composer). Select the relationship that you added in previous step to each field (this is important, otherwise View won't work).
5. You can test your View by entering a Node Id from any existing Concert nodes into Views Preview placeholder for contextual filters. Without given contextual filter, preview will not show you any results (that's expected)

**STEP 2 - OVERRIDE PROGRAM FIELD TEMPLATE**

1. Copy `field.tpl.php` from `modules/field/theme` and place it into your current theme template folder.
2. Rename the file. Now here you need to decide if you wish to override the display of the field "Program" everywhere on your website or only when it is displayed in content type Concert.

**field--field-name--content-type.tpl.php** \- Will target a specific field name within a specific content type. **field--field-name.tpl.php** \- Will target all fields of a specific machine name.

I'd recommend starting with the first choice - **field--field-program--concert.tpl.php**

Clear cache to let Drupal see your new template.

Now remove everything that was originally in that template, you can leave just the top comments for the sake of maintainability, etc. And add the code below - which will embed the view you create in the STEP 1.

```
<?php
print views_embed_view('machine_name_of_the_view', 'machine_name_of_the_block', $element['#object']->nid);
?>

```

`$element['#object']->nid` \- is an argument that you can to your View. It is not absolutely necessary to place it here, because our View already has contextual filter that takes `Content ID from Url` by default. So additional argument just gives another chance to override that argument, or make sure that it will be passed appropriately.

That's it. Give it a whirl. Don't forget to test.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to compare the already saved value of node and updated value?
I want to programmatically compare a field value of a node in `hook_node_update()`. How can I get the already saved and the updated values?

# Answer
My suggestion is using simple way, register custom submit handler then before items saved compare submitted field value with saved value.

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'contenttype_node_form') { // Replace contenttype
      array_unshift($form['#submit'], 'my_custom_submit_handler')
  }
}

function my_custom_submit_handler($form, &$form_state) {
   if(!empty($form_state['values']['nid'])){
   // Load the current node object
  $node = node_load($form_state['values']['nid']);

  // Display the current node object's values
//  dsm($node);

  // Display the submitted values
  //dsm($form_state['values']);
if($form_state['values']['yourfield']['und'][0]['value'] != $node->yourfield['und'][0]['value']){
// do what you want here
  }
 }

```

}
> 1 votes

# Answer
`node_save()`, which invokes `hook_node_update()`, contains the following code.

```
// Load the stored entity, if any.
if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

```

So, every time a node is updated, `$node->original` will contain the node object before it is updated.

To get, for example, the value the *field\_example* field had before the update, you use the following code.

```
$old_value = field_get_items('node', $node->original, 'field_example');

```

To get the updated value for the same field, you use the following code.

```
$new_value = field_get_items('node', $node, 'field_example');

```
> 7 votes

---
Tags: 7, nodes, entities, hooks, updating
---


# Question
Title: custom service respond me : 401 Unauthorized: Missing required argument foo
I have this custom service:

```
function zbs_services_resources() {
  return array(
    'productQuestionForm' => array(
      'actions' => array(
        'send' => array(
          'help' => 'save a FOO entity via send form',
          'file' => array('file' => 'inc', 'module' => 'zbs'),
          'callback' => '_zbs_productQuestionForm_create',
          //'access arguments' => array('note resource create'),
          //'access arguments append' => FALSE,
          'args' => array(
              array(
                'name' => 'foo',
                'type' => 'struct',
                'description' => 'The FOO to create',
                'source' => 'data',
                'optional' => false,
              ),
            ),
        ),
      )
    )

  );
}

```

And this little jQuery code in a simple html test file:

```
$.ajax({
    url: "/rest1/productQuestionForm/send",
    headers: { 'Content-Type': 'application/json','X-CSRF-Token':'MY_WORKING_TOKEN' },
    success: function (res) {
      alert("success");
      console.log(res);
    },
    data : {
      'foo' : 'pippo',
      "type":"page",
      "title":"Page submitted via entity JSON REST",
      "body": {
          "value": "<p>test</p>\n",
          "format": "filtered_html"
      }
    },
    type: 'post',
    dataType: 'json',
  });

```

But when I load the simple test html page I see this in developer suite for the POST url:

> 401 Unauthorized: Missing required argument foo

Where am I doing wrong?

# Answer
The problem is the mismatch between the data type you define for foo (`'struct'`), and what you pass with JavaScript (a string). If you are going to pass a string, then your hook implementation should be the following one.

```
function zbs_services_resources() {
  return array(
    'productQuestionForm' => array(
      'actions' => array(
        'send' => array(
          'help' => 'save a FOO entity via send form',
          'file' => array('file' => 'inc', 'module' => 'zbs'),
          'callback' => '_zbs_productQuestionForm_create',
          //'access arguments' => array('note resource create'),
          //'access arguments append' => FALSE,
          'args' => array(
              array(
                'name' => 'foo',
                'type' => 'string',
                'description' => 'The FOO to create',
                'source' => 'data',
                'optional' => false,
              ),
            ),
        ),
      )
    )
  );
}

```

`'source' => 'data'` is perfectly fine, as shown in the example at `hook_services_resources()`, but notice what the documentation says.

> In the case of 'data' unless you put things in an array, you will get passed to your functions. `'source' => array('data' => 'nid')` will pass them off as a single variable; `'source' => array('data')` will give you all argument values to each argument.
> 1 votes

# Answer
Change

```
'source' => 'data',

```

to

```
'source' => array('data' => 'foo'),

```

Clear the caches, and it should work.
> -1 votes

---
Tags: 7, services
---


# Question
Title: How do I get the fields of form attached with a content type as token?
I do not know is it possible or not. I have a content type for creating tickets. I have a form attached to content type which contains ticket state and ticket assignee fields as drop down. Now I want to create a Rule when state of ticket updated then send an email to ticket creater. The problem is that I could not find the state field values as token.

# Answer
> 1 votes
If I understand your question correctly you want send email after state field changes by Rule:

You should:

1. Create a new rule that will react to the *After updating existing content* event
2. Use the following condition:
Data comparison: *node:field-your-field*(maybe field-state) and *node-unchanged:field-your-field*
Select *Negate: FALSE*
3. Create the action
4. Send the email

---
Tags: 7, forms, rules, emails, tokens
---


# Question
Title: Running Drupal in a Windows environment (IIS, SQL Server)?
We are in the process of evaluating Drupal to replace our in-house .NET CMS. We run an IIS 7.5 web farm with a SQL Server 2008R2 on the back end. To make matters worse, we use sql server merge-replication between our primary and secondary collocation facility. Rebuilding the entire web farm structure would be cumbersome.

Can anyone provide thoughts/feedback/experiences on using Drupal with IIS/SQL server? Bonus points if you know it works sql server merge-replication.

# Answer
> 3 votes
Easiest way is to use the Microsoft Web Platform Installer to install Drupal 7 - http://www.microsoft.com/web/downloads/platform.aspx

The only option it currently provides is using SQL Server as the back-end database, so you should be golden. (The Drupal 6 WebPI installs do not target SQL Server)

I've been running Drupal 7 on a Hyper-V-based VM under Win2k8 R2 with SQL Server Express as the backend DB for a few weeks without incident.

# Answer
> 2 votes
I've had some limited experience with IIS+Drupal. My comments would be -

1. It mostly works out of the box.
2. You may need to do some IIS tweakery to get IIS to "behave", ie doing mod\_rewrite and whatnot. This is all pretty well documented, Drupal is pretty standard PHP app in those regards so the answers don't need to be Drupal specific.
3. There are some Drupal modules which make assumptions about nice URLs (mod\_rewrite) Apache-style functionality and which you need to watch for. Not the general case in my experience.
4. Maintainers are likely to be open to fixing any such issues if you are prepared to help (and focus on their love of cross-compatability rather than pushing the buttons marked "hatred of microsoft").

# Answer
> 2 votes
I've ran Drupal on IIS w/ before with no issues. I haven't specifically used SQL server for the backend though.

The one speedbump I did run into was clean URL rewriting, I was able to use http://www.isapirewrite.com/ to use the existing .htaccess files, rather than having to rewrite the .htaccess file as a IIS webconfig.

# Answer
> 0 votes
We just launched a site using MS SQL and IIS. We had to modify a couple of Contrib modules because they used some of MS SQL's reserved keywords. The biggest offender was the Workbench Moderation module but it was pretty easy to run the patch and make it work. Other than that we did not see too many limitations, as long as you use the API for creating tables and use their data access layer then you will have no problems. The database is very simple and their entity framework is very nice and makes getting things out of the database easy.

We also consumed 4 WCF services with no problem, there is a great module called wsclient which helps you manage all your web service descriptions and use them in your modules.

We looked at a bunch of .NET CMSes and they were all pretty weak compared to Drupal and most of them required the CMS company to do actual development work. We have two sites built in Community Server and one using Kentico and we have had a bad experience with both.

We did not have any issues with rewrites or redirects, we have over 15K aliases and about 3k redirects. On top of this there are about 3K pages which are using Web Services that are powered by wildcards we have created.

I was pretty skeptical at first but Drupal has really proven to me that it can run on IIS and use SQL Server with no problem.

# Answer
> 0 votes
The original question is quite old, and Drupal/Windows/Azure integration has gone great lengths since then.

As of 2016, Drupal is fully compatible with Wincache (the Windows alternative of APC/APCu), MS SQL Server and Azure SQL.

This is a very comprehensive step-by-step install guide:

http://www.drupalonwindows.com/en/blog/installing-drupal-windows-and-sql-server

---
Tags: database, iis
---


title: Local and global copies of module?

text:
# Question
Title: Local and global copies of module?
I have a module I'm developing that will be used by several sites.

I have a "preview" site on the same server that I would like to be able showcase new features in before promoting to the production sites.

I thought I would be able to have the production version in the drupal/modules directory, and the preview version in the drupal/sites/preview\_site/modules directory. I had expected Drupal would load the module from the site's directory and ignore the copy in the global modules directory.

However, when I do this, I get the following error:

> PHP Fatal Error: Cannot redeclare

It would seem that Drupal is trying to load both copies!

Is there some way I can get it to only load the local copy?

Is there a better way to achieve this (I expect lots of people will say don't put the preview site on the production server.)

# Answer
I have discovered that this wasn't a problem after all.

I think the error I initially got (on performing a "clear cache") was caused by the original version of my module already being loaded from global version, and loading again from the local version caused the "redeclare" error.

If I had just reloaded the page, Drupal would now know to load from the local copy, and ignore the global one.
> 0 votes

---
Tags: 8, multi-sites
---


title: Enabling clean URLs cause a 404 error

text:
# Question
Title: Enabling clean URLs cause a 404 error
I am trying to enable clean URL in a Drupal 7 website. The clean URL is supported by server, as I can see the checkbox to enable it, but after enabling it, I am able to access only the front page of the website. For other pages, I get a 404 error. I can see the page just by putting `/?q=` after the website address.

How can I resolve this issue?

# Answer
Add .htaccess file in your drupal folder and the issue with the clean url would be solved.

.htaccess file would look something like

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

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

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

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

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

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value upload_max_filesize 40M
  php_value post_max_size 42M
  php_value default_socket_timeout 600s
  php_value max_execution_time 300s
  php_value max_input_time 600s
  php_value memory_limit 512M
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```

Hope that the answer helps you to clean the URL and you wont have to add the query parameter.
> 1 votes

---
Tags: 7, uri
---


# Question
Title: Count the no of people who viewed a particular blog
Is there any module that could count the no of people who viewed a particular blog?

# Answer
> 0 votes
We would have to simply use to Statistic module that's there in the core. Enabling the module would give you the view count of a node page.

In case if we want to track the activity of the user, we can use Google Analytics module.

# Answer
> 2 votes
Enable the statistics module and using views module create a mini report. Other modules you could use in combination with the statistic module are Visitors module and Counter module

# Answer
> 0 votes
Google Analytics:

> Adds the Google Analytics web statistics tracking system to your website.

---
Tags: 7
---


title: Adding CSS classes to wysiwyg

text:
# Question
Title: Adding CSS classes to wysiwyg
I use wysiwyg with ckeditor, and I was wondering how I would add css styles so a user could, for instance, float images to the left or make other similar changes...?

Thanks!

# Answer
Ckeditor uses the `ckeditor.styles.js` file to define the available styles in the Styles drop down. Documentation in that file states:

```
'Styles' button is not enabled by default in DrupalFull and DrupalFiltered toolbars.

```

If you look at the file, it should be fairly straight forward to modify it using the given examples.

The `ckeditor.styles.js` file can be copied to a directory accessible by Drupal and modified to include your styles. Then you have to configure your CKeditor profile to point to the new file, including any applicable CSS.
> 6 votes

# Answer
Instead of hooking into `ckeditor.styles.js`, we can directly do it on the configuration page of the Format.

WYSIWYG format gives you an option to your own styles and we can simple write css on the basis of those formats.

**Steps to add Styles**

* Login on the site as an Admin.
* Navigate to the Configuration page of the formats. (Configuration » Content authoring » Wysiwyg profiles)
* Edit any of the format.
* Open the **CSS fieldset**.
* Under **CSS classes** textarea, create the style you want to create. Format of it should be

> **Style Name** = html\_element.class\_name

Example of the same is

> **Static Page Title = div.static\_page\_title** (So the name of the **style** is **Static Page Title**, which when applied will **wrap the text in div** adding **static\_page\_title as the class of the div element**.)

***Steps to use it***

* Try creating a content and use the Format in which you have added the Style.
* Under Styles you would see the Style settings that you have created.
* Simply write the test and select the style. After you do that the markup would look something like

`<div class="static_page_title">Testing</div>`
* So we can simply write the css for **static\_page\_title** class and everything would work as expected.

Hope that the answer of mine would be helpful
> 1 votes

---
Tags: theming, wysiwyg
---


# Question
Title: How can I send an email to the previous comment author when a user places a new comment?
I want to get the Email address of last comment's author. Actually, I want to send email by creating a rule when new comment posted and this email will go to the user who commented on node before this new comment.

# Answer
There are two situations and they might be a bit hard to combine. Drupal has a concept of threading comments, where the last comment is not necessarily the last in line. Like this:

```
- Comment 1
  - Comment 3 (reply to comment 1)
- Comment 2

```

Who should get the mail? The poster of comment 2 (the last comment author), or user 1? Or both? Also note that you can disable threading comments on the content type settings page.

In order to send a mail to the author of Comment 1, you can create a Rule on **After Saving New Comments**. Use the **Send mail** action and for the `to:` field you can use the token `[comment:parent:author:mail]`. (The mail of the author of the comment above this one.)

If you want to send a mail to the author of comment 2, your rule gets a bit more complicated. The initial action need to be **Before Saving New Comments** (so last comment is actually the last comment before yours). For the first action choose `Add a variable`, the type is **List of comments** and you choose the value to be `comment:node:comments`. This variable holds all comments on the node. Now you need to find a way to keep removing items from this list and send an email to the last one.

*Below is based on experience and not tested*, but I guess you can add a loop and loop over the items in your newly created variable. Then, in the loop **Add a variable** to contain a comment entity and set it with the current item in the loop. This will redefine this variable for every comment in the list and in the end this variable will hold the last comment. Then *below* (not in) the loop, add your mail action and use the author of your newly created variable.

If you want to send a mail to all commenters, place the mail action within the loop (you can omit the comment variable in this case).

**Update**

This can also cause the author of comment 3 to get a mail triggered by comment 4:

```
- Comment 1
  - Comment 3 (reply to comment 1)
- Comment 2
- Comment 4

```

If you want to have more control, you'll need to create a Rules Component and call that component from the loop. Within the component you can add conditions to check if the comment has parents and skip the variable assignment based on that.
> 3 votes

---
Tags: 7, users, rules, comments
---


# Question
Title: Command to start nodejs? Server.js and app.js missing
The outdated documentation for drupal integration of nodejs using the nodejs module instructs me to start nodejs with the command `node server.js`.

But neither server.js or app.js (replacement to server.js) exists

I can see a file called nodejs.js but running `node nodejs.js` produces this error;

```
ReferenceError: jQuery is not defined
    at Object.<anonymous> (/data/disk/o1/static/hood-7.43.1/sites/all/modules/nodejs/nodejs.js:132:4)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

```

What is the command for starting nodejs?

# Answer
Turns out I had incorrectly upgraded the 7.x-1.10 module incorrectly. From version 7.x-1.1 you can no longer merely overwrite the old module with the new module as the installation process is different.
> 0 votes

# Answer
If you're downloading the app from github directly, follow these instructions:

1. Download the archive
2. Extract to a folder oustide of Drupal's root (this app is separate to your Drupal installation so shouldn't be within)
3. `cd` to the folder and run `npm install`
4. Run `cp nodejs.config.js.example nodejs.config.js`, edit the resulting file as required
5. Run `node app.js`

Voila, server up and running.

If you're using the `npm install drupal-node.js` approach, the instructions are a bit unclear. To clarify:

1. Create a folder outside of the Drupal root
2. `cd` to it and run `npm install drupal-node.js`
3. Run `cp node_modules/drupal-node.js/nodejs.config.js.example nodejs.config.js`, edit as required
4. Run `node node_modules/drupal-node.js/app.js` to start the server

You should see the same result as the first method.
> 1 votes

---
Tags: javascript
---


title: Assign email on user registeration

text:
# Question
Title: Assign email on user registeration
I have a custom user `email` field, I want when the user signs up to automatically set the email for he/she.

For example, when the username field is `user1` I want set the email to `user1@mydomain.com` and save it in email field.

How can I do this?

# Answer
If you'd like to customize the user registration form, you're probably looking at a custom module to take care of this; an invocation of `hook_form_alter()` can step in and alter the behavior of the user registration form. For example, adding the following functions to MYMODULE:

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

  // Disable the email field
  $form['account']['mail']['#access'] = FALSE;

  // @TODO: Override validation functions in $form['#validate']
  // that check the mail field

  // Replace the user registration form submission with
  // the function MYMODULE_form_user_register_form_submit
  $form['#submit'] = array('MYMODULE_form_user_register_form_submit');
}

// Alter the disabled mail field before
// submitting registration form to user_register_submit()
function MYMODULE_form_user_register_form_submit($form_id, &$form_state) {
  // add '@mydomain.com' to the submitted username field
  $form_state['values']['mail'] = $form_state['values']['name'] .  '@mydomain.com';
  user_register_submit($form_id, $form_state);
}

```

This only get you partially there, as overriding such key functionality requires many scenarios to validate now that a key assumption is gone (e.g. what happens when someone enters an email for a name, what happens when a user needs to recover password, etc.).

It might be helpful to look at the source code of the Optional mail on register module to see how that is accomplished so you can under how modules can override Drupal's user registration functionality.
> 2 votes

---
Tags: users, emails
---


# Question
Title: Login and get homepage content with a Bash script
In some developments for drupal 7, I need connect with one user via a bash script then get the content of the connected homepage.

After several searches, my last try :

```
URL="https://www.mainsite.com/subsiteone/"

curl -s -f -o $output -H "Content-Type:application/xml" --insecure  $URL  -w "@formatsender.conf"  > ./test.txt

formid=$( grep 'input type="hidden" name="form_build_id"' $output | cut -d"=" -f4 | sed -e 's/"//g' | sed -e 's/\/>//g' )
echo $formid #show the good pofm id

curl --request POST ${URL} --data "name=usernameone%26pass=userpasswordone%26form_build_id=$formid%26form_id=user_login"

```

the last curl shows the content of the login page (not connected) without any error message. I don't understand where is my mistake..

# Answer
> 2 votes
You might want to double checking your encoding or the headers that you're sending over that might cause the problem. I've found trying to do this with a pure Bash solution very fickle at times. Here's an example function I've used that will login into a D7 site on the **/user** page (an easier manner since every D7 install can be logged in from that path).

```
#!/bin/sh

# https://gist.github.com/cdown/1163649
#Usage: urlencode "string"
function urlencode() {
  old_lc_collate=$LC_COLLATE
  LC_COLLATE=C

  local length="${#1}"
  for (( i = 0; i < length; i++ )); do
    local c="${1:i:1}"
    case $c in
      [a-zA-Z0-9.~_-]) printf "$c" ;;
      *) printf '%%%02X' "'$c" ;;
    esac
  done

  LC_COLLATE=$old_lc_collate
}

#Usage: login "user" "pass"
function login() {
  URL=https://www.example.com/user
  name=$(urlencode "$1")
  pass=$(urlencode "$2")
  post_data="name=$name&pass=$pass"

  #Retrieve login page, login form, & input fields.
  login_page=$(curl -s -H "Content-Type:application/xml"  "$URL")
  login_form=$(echo $login_page | grep -o '<form[^>]*action="/user"[^>]*id="user-login"[^>]*>.*</form>')
  login_input=$(echo $login_form | grep -o '<input[^>]*/>')

  #Create Post Body
  while read -r input; do
    input_field=$(echo "$input" | sed -e 's/.*name="\([^"]*\)".*/\1/')
    if [[ $input_field != "name" && $input_field != "pass" ]]; then
      input_value=$(echo "$input" | sed -e 's/.*value="\([^"]*\)".*/\1/')
      input_field=$(urlencode "$input_field")
      input_value=$(urlencode "$input_value")
      post_data="$post_data&$input_field=$input_value"
    fi
  done <<< "$login_input"

  # Depending on your hosting environment you might need additional headers to make yourself not look like a bot
  user_agent="User-Agent:Mozilla/5.0 "
  referer="Referer:https://www.example.com/user"
  origin="Origin:https://www.example.com"
  content_type="Content-Type:application/x-www-form-urlencoded"

  # For further authenticated requests, you will need to parse output "Set-Cookie: ..." and set
  # the session cookie in a -H "Cookie: ..." option
  curl -s -L -H "$content_type" -H "$user_agent" -H "$referer" -H "$origin" --request POST "${URL}?destination=/" --data "$post_data"
}

login 'USER' 'PASS'

```

I've found logging into Drupal via Bash much easier with if you can work with a scripting language that has built in HTTP clients & parsers. Depending on your scenario, you might want to consider that if you need a more robust solution.

# Answer
> 0 votes
When you post the user credentials to Drupal, I am pretty sure you need to POST it to `/user/login` and not to the front page.

Then after loggin in, Drupal's default behavior is to redirect the user to `/user`, not the front page. You might succeed appending `?destination=<front>` to the request path, use Rules to redirect the user after login, or use Login Destination to make sure the site will present you the front page.

You might want to try something like this for your last line:

```
curl --request POST ${URL}/user/login?destination=<front> --data "name=usernameone%26pass=userpasswordone%26form_id=user_login"

```

I believe `form_build_id` is not mandatory, but I am not really sure so you might have to add that. I omitted it in the example.

---
Tags: 7
---


# Question
Title: Auto create nodes from external RSS source
The scenario I am trying to fulfil is the automatic creation of Drupal nodes from an RSS list.

At the initial execution of cron, the module, custom/contributed, should parse some remote RSS and for each entry in the RSS a Drupal node with matching title, body etc is created.

The next hour when cron fires, any matching content previously created is ignored. Only when there is a new entry in the RSS should new node(s) be created.

**Is there an existing module for doing what I have described above?** OR, **Can anyone direct me on how best to implement such a service?**

Thanks.

# Answer
The feeds module can 'Import or aggregate RSS/Atom feeds'. https://www.drupal.org/project/feeds

You can set how often it imports and map to fields.

Here's a guide on how to create/edit importers: https://www.drupal.org/node/638804
> 0 votes

---
Tags: 7
---


# Question
Title: Trying to create a user with an entity reference taxonomy term using services
So I've been trying to create a user with an entity reference taxonomy term, however for some reason it doesn't seem to work.

I've noticed that it depends on the widget used, but I've tried every combination of widgets and data, and it doesn't appear to work.

Here's an example of one way:

```
                    "field_likes": {
                        "und": "1"
                    }

```

I've also tried this, also for example:

```
                    "field_likes": {
                        "und": [
                            {
                                "target_id": 1
                            }
                        ]
                    }

```

Is there anyway to add taxonomy terms as an entity reference on a user that will work? Has this changed, or am I doing something wrong?

# Answer
I was able to get it working with the following on checkboxes and select:

```
"field_likes": {
"und":{
"target_id": "1"
      }
}

```

This technically solves the problem, though I'm not sure how to send up multiple values this way.

EDIT:

Here is the actual solution, which not only allows you to put in entity reference taxonomy terms, but multiple as well:

```
"field_likes": {
                 "und":{
                         "target_id": "1",
                         "target_id_1": "2"
                        }
                }

```

This is with the select list widget, which I think is important for this particular example (based on other links I've been reading).
> 0 votes

---
Tags: entities, services
---


# Question
Title: Passing Arguments between an EntityReference field and an EntityReference View
So I'm trying to figure out how to filter a couple of entityreference view I'm using to populate an entityreference field. It has the option to pass arguments to the view, but I'm not sure HOW to do that.

In one node add/edit form I need it to take the values of two taxonomy terms. Those terms would then filter down the list and only return values that included those values. The Taxonomy terms can have three values though.

I also have another form that I need to be able to filter based on what name is in the Authored by Field. I need to be able to pass that back to the view and only return nodes that are authored by the authored by user.

I'm not sure how you set that up and I'm trying to find documentation to figure it out. So far no luck.

If anyone has any ideas, let me know.

# Answer
> 2 votes
Add a contextual filter of Has Taxonomy Term ID

* Select Provide Fixed Value and type Fixed Value. For fixed value type the ID's of your terms separated by a comma. (You can find the ID of your taxonomy terms inside the edit url when you edit your terms)

Scroll all the way down to the MORE section.

* Click on MORE and check mark allow multiple values.

---

For your other view, use Author Uid and follow the picture below.

---
Tags: views
---


title: Creating trigger function in Postgres

text:
# Question
Title: Creating trigger function in Postgres
I was developing my own customized module in Drupal 7. Is there any way I can create at run-time a trigger function in PostgresSQL? A sample scenario is when after successfully deleting a record in a particular table.

# Answer
You can use the `db_query()` function for that:

> Executes an arbitrary query string against the active database.

e.g.

```
db_query('postgres-specific SQL here');

```

Note: if the DBMS you're connected to at any point *isn't* pg, and it doesn't understand the statement you're executing, that code will throw an exception. Probably best to catch that and handle if your module needs to be portable.
> 0 votes

---
Tags: 7, database
---


# Question
Title: Displaying the submitted values in a table
I created a custom form and after the form is submitted I need to display the submitted data in a table. This seems like a very simple problem. I am able to use `dpm()` and `drupal_set_message()` to display data submitted from the form in `mymodule_form_submit($form, &$form_state)`; however, I can't output it to a table.

I have 3 field values

```
$form_state['redirect'] = 'some/path/' . $form_state['values']['my_value'];

```

Using this I can send just 1 value. But how can I send an array with this? Query string may appear to be very long.

# Answer
> 0 votes
You don't need to redirect the form like that: a form submission handler can pass data to the form builder using `$form_state`; in this way, you don't have any limit for what you can pass back to the form builder.

It's enough the form submission handler uses the following line.

```
$form_state['rebuild'] = TRUE;

```

Then it saves in `$form_state` the values to pass back to the form build, being careful not to use the same index used for other purposes, from Drupal, or your module. Usually, `$form_state['storage']` is used for that purpose, as explained in `$form_state` keys.

> **$form\_state\['storage'\]**
> When building complex forms that require multiple steps for completion (for example, a three-page survey), it's necessary to preserve the data from all steps so that they can be processed together at the end. (And, on occasion, to vary the contents of one step based on the input from the previous one). Any data placed in the 'storage' bin of the $form\_state collection will automatically be cached and re-loaded when the form is next submitted, allowing your code to accumulate data from step to step and process it in the final stage without any additional code. Developers who want more control can use their own caching mechanisms to store temporary form data (the user session and hidden form fields are two popular alternatives), but the 'storage' bin is automatically handled for you by the form API.

That is for Drupal 6; for Drupal 7, see `drupal_build_form()`.

> storage: `$form_state['storage']` is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where **application-specific data was stored for communication between the submit, validation, and form builder functions**, especially in a multi-step-style form. Form implementations may use any key(s) within `$form_state` (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses `$form_state['node']` in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.

If you really need to print the data in another page, then save the data in `$_SESSION`, instead of passing that as GET data.

# Answer
> 0 votes
**For Drupal 7:**

```
function youth_fest_form($form, &$form_state) {

    $form['can_id'] = array(
             '#type'=>'hidden',
             '#value' => isset($value['can_id']) ? $value['can_id'] : '' ,
         );

    $form['firstname'] = array(
            '#type' => 'textfield',
            '#title' => 'Full Name',
            '#size' => 30,
            '#maxlength' => 50,
            '#weight'=>1,
            //'#default_value'=>t('First Name'),
            '#required' => TRUE,
            '#attributes' => array(
                'placeholder' => t('First Name'),
                ),
            '#prefix' => '<div id="wrapper"><div id="leftcolumn">',
            '#suffix' => '</div>',

        );

    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('SUBMIT'),
        '#weight'=>13,

      );

      return $form;

    }
function youth_fest_form_submit($form, &$form_state) {
$data = db_insert('youth')
  ->fields(array(
    'first_name'        =>  $form_state['values']['firstname'],
    ))
  ->execute();
if(isset($data)){
    drupal_set_message('Values inserted successfully!');
  }
}

```

**submitted result in a table:**

```
function youth_admin_content_page(){

 $header = array('First Name', 'Last Name');

  # set the database table
  $query = db_select('youth', 'p')->extend('PagerDefault');

  # get the desired fields from the database
   $query->leftJoin('file_managed', 'fm', 'fm.fid = p.file');

   $query->fields('fm',array('filename','uri'));

   $query->fields('p', array('candidate_id', 'first_name'))
    ->limit(3);

  # execute the query
  $results = $query->execute();

  # build the table fields
  $rows = array();
  foreach ($results as $row) {

    $rows[] = array("<a href=\"/projects/edit/" . $row->candidate_id . "\">" . $row->first_name . '</a>',
                    $row->last_name,
                   '<img src="'.$optimageurl.'" width="100" height="100">',

    );
  }
  $output = theme('table', array('header' => $header,'rows' => $rows ));
  $export = 'Export';
  # add the pager
  $output .= theme('pager');
  return $output;

}

```

---
Tags: 7, forms, redirection
---


# Question
Title: How do I handle third-party API credentials in settings?
I am building a module that will need to integrate credentials for the 3rd party service in Drupal 8. The module's admin panel should remember the credentials and use them to interact with the service, but still hold them secure. Storing the credentials un-encrypted or exporting them in config with drush cex can pose a threat. How are such cases to be handled in Drupal 8? What is a good way to handle secure 3rd party credentials with Drupal 8?

Details: A module integrating with the 3rd party online service. This service provides credentials, that the user inserts in the module's admin form, and then can use the services. It won't do to hard code the credentials in PHP, and saving them as config in Drupal 8 will result in them being exported with drush cex. So, there is a need to store secure data in the settings, and keeping it from export when config is exported.

# Answer
> 5 votes
The key module provides a framework for abstracting key storage from modules. The module provides 2 key providers (plugins) out of the box: config and file. It is possible to implement a key provider plugin for some arbitrary storage such as what the encrypt module provides.

Note that a web site's actual security risk for using a particular key provider depends more on security procedures and infrastructure.

---
Tags: 8, security, configuration
---


# Question
Title: Rule works but produced "err_empty_response" error when I want to edit it
So I have created a rule, that works, does what it should exactly do (so the syntax and configuration is okay), but after creating it and waiting a while, the rule becomes un-editable and the edit page gives just WSOP, while disable, export, delete etc still keeps working. I tried manually recreating the rule, it again works and is editable for a while, until it does the same thing. There is also no error generated on apache when this happens. I also tried it on multiple computers and browsers. I have clean path URL enable though, could that be an issue? Here is the exported rule code

```
{ "rules_odeslat_pp" : {
    "LABEL" : "odeslat PP",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail" ],
    "ON" : { "user_update" : [  ] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "account" ],
          "roles" : { "value" : { "4" : "4", "6" : "6", "3" : "3" } },
          "operation" : "OR"
        }
      },
      { "NOT data_is_empty" : { "data" : [ "account:field-pp-odeslany" ] } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : [ "account:field-stav-uctu" ] },
          "PROVIDE" : { "variable_added" : { "pz" : "PZ" } }
        }
      },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "pz" ],
            "op" : "-",
            "input_2" : [ "account:field-pp-odeslany" ]
          },
          "PROVIDE" : { "result" : { "ns" : "novy stav" } }
        }
      },
      { "data_set" : { "data" : [ "account:field-stav-uctu" ], "value" : [ "ns" ] } },
      { "data_set" : { "data" : [ "account:field-stav-uctu" ], "value" : [ "ns" ] } },
      { "mimemail" : {
          "key" : "vyplata",
          "to" : [ "account:mail" ],
          "cc" : [ "" ],
          "subject" : "Informace o Vaší odměně",
          "body" : "Važený zpracovateli,\u000D\u000A\u000D\u000Aadministrátor webu právě odeslal [account:field_pp_odeslany] Kč do účtárny! Nový stav vašeho účtu na webu Prostudent: [account:field_stav_uctu] Kč. \u000D\u000A\u000D\u000APokud nebudou peněžní prostředky připsány na Váš účet do 15. dne v měsíci, obraťte se prosím na zákaznickou linku a problém rádi vyřešíme.\u000D\u000A\u000D\u000ATento email je pouze informativní, neodpovídejte na něj.\u0022,",
          "plaintext" : "Važený zpracovateli,\u000D\u000A\u000D\u000Aadministrátor webu právě odeslal [account:field_pp_odeslany] Kč do účtárny! Nový stav vašeho účtu na webu Prostudent: [account:field_stav_uctu] Kč. \u000D\u000A\u000D\u000APokud nebudou peněžní prostředky připsány na Váš účet do 15. dne v měsíci, obraťte se prosím na zákaznickou linku a problém rádi vyřešíme.\u000D\u000A\u000D\u000ATento email je pouze informativní, neodpovídejte na něj.\u0022,",
          "language" : [ "" ]
        }
      },
      { "data_set" : { "data" : [ "account:field-pp-odeslany" ] } }
    ]
  }
}

```

# Answer
> 2 votes
Have you tried this on multiple servers as well? It is likely something on the server, so other browsers and computer won't make the difference. You did not specify the Drupal version but I ran into a similar situation with Drupal 8 while editing Views.

For me the solution was to increase the PHP memory limit. The linked page shows several ways to do this, but I chose to do it in the php.ini file. I believe it is `256M` now.

---
Tags: rules
---


title: How to load jquery in twig file

text:
# Question
Title: How to load jquery in twig file
I need to run a jQuery file in a twig file in order to bind aqua lift segments. but jQuery is not loaded yet . How can I load jQuery at this point without loading it twice? thanks

# Answer
I think your question is that you want to put inline javascript in twig templates, but it does not work, because jquery is not loaded yet?

You can override the default that the libraries are loaded in the footer and put jquery and any of your own js in the header:

mytheme.libraries.yml:

```
mylibrary:
  version: 1.x
  header: true
  js:
    js/myjavascript.js: {}
  dependencies:
    - core/jquery

```

mytheme.info.yml:

```
libraries:
  - mytheme/mylibrary

```

The important part is `header: true`.

If you make a dependency on `core/jquery` for the header, jquery is not loaded a second time in the footer, even if there are multiple dependencies for `core/jquery` by other libraries.

Now you can put your jquery dependend js code in the header (in this example in myjavascript.js) or put inline js in twig templates.
> 5 votes

# Answer
```
{{ attach_library('core/jquery') }}

```
> 3 votes

---
Tags: 8, javascript
---


# Question
Title: Kint breaks in template and doesn't allow me to view anything
In my template I am trying to view the contents of Childen in a form template.

```
<form{{ attributes }}>
  {{ kint(children) }}
</form>

```

However, the result I get is a useless broken kint message, that doesn't allow me to expand any of the fields or view any other information.

>

Any ideas?

# Answer
> 1 votes
Deactivate the BigPipe module, it causes some errors in Google Chrome when the user is logged in.

There's no error in Chrome if you aren't logged in. Firefox and Safari will still work with Kint and BigPipe enabled.

---
Tags: 8, debugging
---


# Question
Title: How do I use Url::setUnrouted() in a custom module?
How do I use `Url::setUnrouted()` in a custom module?

If I call this method I get the following error:

> Call to protected method `Drupal\\Core\\Url::setUnrouted()`

# Answer
> 5 votes
`Url::setUnrouted()` is really an internal method used by the `URL` class. It is used by the static constructor `Url::fromUri()` when the URI passed as argument isn't a route.

In general, you should create URL from one of the static constructor functions, and then use the public methods to change anything that you need. And, paths in your own code should be set up as routes, whenever possible.

If you really need to create an unrouted URL to a static resource that can't be handled through other method (eg, JS and CSS should be handled using #attached), then you would do something like the following:

```
$url = Url::fromUri('base:some/path/foo.txt');

```

---
Tags: 8, uri
---


title: Login with Facebook or Google+ account

text:
# Question
Title: Login with Facebook or Google+ account
I want users to be able to log in (signup) in site with their Facebook or Google plus account. But I didn't find anything for Drupal 8.

Is there any module or solution for doing this job or I should downgrade and use Drupal 7 in our project?

# Answer
> 1 votes
This specific signup type is called OpenID. And it allows an external login provider to login users on your site.

You can have a look at OpenID Connect module. Which has a beta version for Drupal 8 available, and according to the module page already ships with a Google implementation.

> OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.

I am not sure about Facebook, but it might be that is in another contrib module or easy to implement yourself. (I didn't look for it.)

# Answer
> 0 votes
You can use module Simple OAuth. Some more details about it, from its project page:

> ... is an implementation of the OAuth 2.0 Authorization Framework: Bearer Token specification.
>
> Using OAuth 2.0 Bearer Token is very easy. See how you can get the basics working in less than a minute!
>
> This project is focused in simplicity of use and flexibility. When deciding which project to use, also consider other projects like OAuth, an OAuth 1 implementation that doesn't rely on you having https in your production server.

---
Tags: users, 8
---


# Question
Title: Using drupal_add_css to dynamically add inline CSS based on term reference
I'm trying to create a CSS class called `.bg-unit-color` which will change depending on the taxonomy reference chosen

I've set up a course category taxonomy and then set up a color field within it using jQuery Colorpicker module. I've got to the point where I can render the color in my node--example.tpl.php file with the following:

`<?php
$term=taxonomy_term_load($node->field_example_category['und'][0]['tid']);
$category_color=field_view_field('taxonomy_term',$term,'field_example_category_color');
echo render($category_color);
?>`

I've also used the drupal\_add\_css function in my template.php file, so this works:

`$new_color='black';
drupal_add_css(".bg-unit-color {background-color: $new_color;}", 'inline');`

However I can't marry the two together to create what I'd like to do which is this:

`drupal_add_css(".bg-unit-color {background-color: $category_color;}", 'inline');`

Any help would be massively appreciated. Thanks in advance

# Answer
If using render you should attach the css to that render array.

```
$term = taxonomy_term_load($node->field_example_category['und'][0]['tid']);
$category_color = field_view_field('taxonomy_term',$term,'field_example_category_color');
$name = $term->name;
$category_color['#attached']['css'][] = array(
  'data' => ".bg-unit-color {background-color: $name;}",
  'type' => 'inline',
);

```
> 1 votes

# Answer
To update the classes on a node based on a field value you can use `template_preprocess_node()`. I would put my CSS into a file, have the file attached to all pages via the theme, and then set a class on the node's wrapping div:

```
function mytheme_preprocess_node(&$vars) {
  if($vars['node']->type == 'my_content_type') {
    $term=taxonomy_term_load($vars['node']->field_example_category['und'][0]['tid']);
    $category_color=field_view_field('taxonomy_term',$term, 'field_example_category_color');
    $vars['classes_array'][] = drupal_html_class($category_color);
  }
}

```

A non-code solution would be to use the Field Formatter CSS Class module.
> 0 votes

---
Tags: theming
---


title: Configuration management import error

text:
# Question
Title: Configuration management import error
I use a CMI workflow with Git.

1. I made configuration changes on Dev
2. pulled them into Production
3. now when I go to `admin/config/development/configuration` and try to import All I get this error:

> The configuration cannot be imported because it failed validation for the following reasons: Entities exist of type Taxonomy term en Vocabulary Catalog. These entities need to be deleted before importing.

What do I have to do now?

# Answer
> 1 votes
Exactly what it says. You seem to be deleting the Catalog vocabulary. You need to delete all terms in it first.

---
Tags: 8, version-control, configuration
---


# Question
Title: How to enable user registration, but don't allow any of those users to login?
I want to use the user registration page to collect user data and use its email verification checking to filter out fake users. But the thing is I don't want these users to be able to login to the site. How can this be done in Drupal 7?

**Note**: So no login at all. I just want to use the registration system to send them an email to verify their account.

# Answer
### Question refinement

This is a pretty tricky question, especially the "***... no login at all ...***" part of it. IMO you have to allow at least somebody with some specific role to perform a login ... If you don't, then even an admin (or `user/1`) cannot login. Which also implies you can't just deny access to the login URL for everybody (how else would an admin perform a login?).

### Proposed solution

Below is a solution to "kick everybody (except admins) out right after login, but only after you send such user an appropriate eMail".

Here is the rule (in Rules import format) that should answer your question:

```
{ "rules_redirect_to_logout_except_for_role_id3" : {
    "LABEL" : "Redirect to logout except for role ID3",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[account:mail]",
          "subject" : "No login allowed",
          "message" : "You just completed a login to [site:name], located at [site:url].\r\n\r\nHowever, at this time we do not allow any login ...\r\n\r\nThanks anyway for validating some of your account data, such as your eMail ID.",
          "language" : [ "" ]
        }
      },
      { "redirect" : { "url" : "user\/logout" } }
    ]
  }
}

```

The rule will be triggered (Rules Condition) right after login was completed. For any user who does not have the role that matches "`role id = 3`" (= Rules Condition), aka for any user who is not an administrator, it will perform these Rules Actions (in the order specified):

1. Send an appropriate eMail to the user that completed the login (since the user is logged in, you have the user's eMail Id available as part of the user's account info).
2. Redirect to the page `user/logout` (= force the user to be logged out again).

If you have the Rules UI enabled, you can just import the above rule and adapt the value (=3) of the role id to fit your needs. With that you solved your question.

Obviously, you'd have to adapt the eMail subject and content to fit your needs. Possibly you may also want to use some other (or additional) role IDs that you want to allow to login anyhow.

With the above approach, all what's left to do to fully answer your question, is to create an inventory (a view?) of all users and check their last login date. Those accounts that were created X hours/days ago but for which no login was completed ever, are the fake users you're looking for (because the eMail ID they entered during registration was invalid, or such users didn't really want to get registered so they never confirmed their registration request via an appropriate, temporary, login).

**Note**: by default the rule is disabled (so don't forget to enable it also).
> 1 votes

# Answer
You could use Rules

Event: After saving a new account

Action: Block a user \>\> data selector: account
> 2 votes

# Answer
Add a validation hook to your login form and make it fail.

```
/**
 * Implementation of hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'user_login') {
       array_unshift($form['#validate'], 'YOUR_MODULE_login_form_validate');
    }
}

function YOUR_MODULE_login_form_validate($form, $form_state) {
    form_set_error('','Your user is not enabled to login');
}

```

This can be useful to you
> 2 votes

# Answer
The Easiest way to do this is, go to `admin/config/people/accounts` and choose **Visitors, but administrator approval is required** and save.
by selecting this option user can register on site and by default they `status` set to `blocked` and if admin approve them , they can log in to site otherwise **they can not login site(block user can not login to site)**. There is not need any additional Rules or Code.
> 2 votes

---
Tags: 7, users
---


title: Entity reference widget

text:
# Question
Title: Entity reference widget
I know that in Drupal 8 the taxonomy term reference is deprecated and it's implemented by an entity reference in Drupal 8 Core.

Is there any widget to select items by checkbox list instead of the default autocomplete entity reference widget?

# Answer
> 8 votes
Yes!!

1. Go to Manage form display of the content type
2. Go to the entity reference field and there you can find a list of options including checkbox .

# Answer
> 5 votes
## Drupal 8

Go to the *Manage form display* tab.

## Drupal 7

Go to *Manage fields* tab, and click on the blue widget link.

It takes you a new page, where you can change the widget to *Check boxes/radio buttons*.

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


title: The <front> route 's path

text:
# Question
Title: The <front> route 's path
My `<front>` and `<none>` route is now using one of my view path... I think it's because I delete the default home view.

I don't need it because my home page is a Panels Page...

How to set the `<front>` route to use an other path ?

EDIT :

Exemple: i've a view called myContentAdminView, with this url defined : /my-content-admin-view.

if i look in the bdd, in the router table, the both path of the front\> and none\> route are set to /my-content-admin-view. this values are sync with the url view, i don't know why and how to change that.

The front\> is use for exemple when you disconect. The none\> route is use by the MenuBlock to check if a user has the right to see a link with no route (like this one : '#a-anchor-link')

# Answer
> 2 votes
The defaults for these routes are defined in system.routing.yml:

```
'<front>':
  path: '/'
  defaults:
    _title: Home
  requirements:
    _access: 'TRUE'

'<none>':
  path: ''
  options:
    _no_path: TRUE
  requirements:
    _access: 'TRUE'

```

The router table is rebuilt every time you clear the cache. Then all static routes defined in yaml-files are collected and put in the router table.

If you get other path values for these routes, then you must have overridden this somewhere, for example in a view.

This has nothing to do with the setting in site configuration.

If you a looking for a specific path you can search in all `*.routing.yml` files for the static routes. Most of the dynamically generated routes probably are somewhere in the config files. You can export the full config of your site (admin/config/development/configuration/full/export) and search there for a specific string.

---
Tags: views, 8, routes
---


# Question
Title: How to modify HTML layout inside a View template
I am very new to Drupal and this is my first post in this community. What I am trying to achieve I know may be very simple but just don't know how! So I am looking forward for expert help.

First please see the screenshot:

**Below is what I want to achieve:**

1. WHITE boxes are laid out as float: left;
2. I want A, B and C to shift below their respective titles, i.e. at A1, B1 and C1 spots respectively.
3. I want to make the TITLE + A1 to be under the same container so the container can float left itself. Same with TITLE + B1 and TITLE + C1

I copied **views-view-unformatted.tpl.php** file to my custom theme folder. The code snippet is rendering the data fine:

`<?php foreach ($rows as $id => $row): ?>
 <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"'; } ?>>
 <?php print $row ?>

<?php endforeach; ?>`

But I want each of the field in `$row` to be printed in a way I want, e.g.:

`<?php foreach ($rows as $id => $row): ?>
 <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"'; } ?>>

 <?php print $row->title ?>

 <?php print $row->body ?>

<?php endforeach; ?>`

I believe there is a way to do it but don't know how. `$row->title` or `$row->body` is actually printing (rendering) nothing.

Also, if I modify **views-view-unformatted-tpl.php** it will affect the entire site. So I want a **separate view** for this purpose. How to do this?

# Answer
**views-view-fields--\[view-name\]--machine name.tpl.php**

Ex: `views-view-fields--hello-world--block-1.tpl.php`

```
<div class="picture">
  <?php print $fields["field_image"]->content; ?>
</div>

<div class="text-wrapper">

  <div class="title">
     <?php print $fields["title"]->content; ?>
  </div>

  <div class="small-summary">
     <?php print $fields["body-summary"]->content; // if you r using a body summary ?>
     <?php // if you are using an actual field then use:  print $fields["field_name"]->content; ?>
  </div>

</div>

```

CSS

```
.picture { float: left; }

```
> 1 votes

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


# Question
Title: How do I list all blocks with PHP enabled inside?
I added a custom block that uses PHP, and now I get the following notice message:

> Trying to get property of non-object in eval() (line 5 of /public\_html/modules/php/php.module(80) : eval()'d code).

I am trying to find which one is causing that notice, and since I have many blocks, I would rather do it without using the user interface.

Is there a way to get a list of blocks using PHP? I would be happy also with a solution using the Views module, as long as I don't need to look at the settings of each block, one by one.

# Answer
If you want to find all custom blocks that have PHP code as their input format, you can query the `block_custom` table. The `format` column will contain the key `php_code`.

```
$blocks = db_select('block_custom')
  ->fields('block_custom')
  ->condition('format', 'php_code')
  ->execute();
foreach($blocks as $block) {
  // @TODO: Add your own actionable code
}

```
> 3 votes

---
Tags: 7, blocks
---


title: Content translation of paragraphs

text:
# Question
Title: Content translation of paragraphs
I'm trying to translate paragraphs in Drupal 8. According to this bug report, which is marked as fixed, it should work.
*#2543258: Entity references of untranslatable fields are not displayed in the correct translation* is supposed to be fixed as well.

I don't know if this has anything to do with it. Right now, I'm stuck and I even don't know if this really *should* work or not.

I'm doing the following:

1. In hook\_preprocess\_page there is $vars\["node"\] (as usual available via argument $vars)
2. On this node (could in fact be any arbitrary Node object, I guess) I will call $node-\>getFields()
3. One of the fields is a pararaph node ("field\_sidepane")
4. I call "$field-\>view()" on this field to render the whole field (i.e. everything that's in the sidepane) at once. view() doesn't seem to support a second argument for the langcode or anything.
5. The sidepane contains multiple paragraphs (Cardinality=-1). One of these paragraphs contains a field "field\_body" of type "text\_long".
6. This field is marked as translatable (under the Paragraphs section of the config page). field\_sidepane by itself (appearing under the Content section of the config page), however, is not marked as translatable.
7. Apart form the minor glitch, that these paragraphs are wrongly labeled as "All languages" (which I think is https://www.drupal.org/node/2463575) everything works great during edit-time. I can edit text separately for the different languages etc.
8. On the page, however, only the primary language is ever shown.

I thought it would be straightforward but I turns out to be surprisingly difficult. In the class Drupal\Core\Entity\Entity\EntityViewDisplay I discovered the following section:

```
      // The language of the field values to display is already determined
      // in the incoming $entity. The formatter should build its output of
      // those values using:
      // - the entity language if the entity is translatable,
      // - the current "content language" otherwise.
      if ($entity instanceof TranslatableInterface && $entity->isTranslatable()) {
        $view_langcode = $entity->language()->getId();
      }
      else {
        $view_langcode = NULL;
      }

```

I've found that if I set `$view_langcode` to `NULL`, it seems to work. Obviously, it gets the language from the main entity. But I don't know how I can change this in any way (either programmatically nor via the UI). Even if I explicitly use `$node = $node->getTranslation("en");` and call `getFields()` on the result, it doesn't seem to work. I could find no way whatsoever to render the field in the translated language.

# Answer
> 1 votes
Yes, that API doesn't support passing in the language.

I would recommend you use a view mode for what you are doing. You can click that together in the UI, configure the fields you want to see there and then just call $node-\>view('your\_view\_mode'). That should just work.

You could also use the Entity View block provided by ctools module, then you can place your sidebar as a block in a region and don't need any custom code at all.

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


title: Loading a script before another one

text:
# Question
Title: Loading a script before another one
I have created a dependency like the following, but it seems that acquia\_lift is still not running before gtmscripts. How can I achieve this?

```
 GTMscripts:
 version: 1
 header : true
 js:
   assets/js/GTMscripts.js: {}
 dependencies:
    - acquia_lift/acquia_lift

```

# Answer
As long as Replace custom weights with dependencies in library declarations is not fixed, you have to use weights to control the priorities of JavaScript files.

```
 js:
   assets/js/GTMscripts.js: { weight: 10 }

```
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How to render a contact form as rendered entity
I have a question about rendering a contact form as a rendered entity. I have a field in my contenttype where form should be displayed. The field has the type Contact form.

In the Manage display section in the contenttype where the field is added i got only the possibility to choose Label, Entity ID or Hidden for the format.

On the page itself i got only a link to the page where the form is embedded. I searched about a solution and got something like loading and handling the form with an own module, loading the form in a hook or create a block.

So are those the only possiblities or is there a way to include the form like another entity reference (where i choose Rendered entity as the format).

# Answer
> 8 votes
Use https://www.drupal.org/project/contact\_storage.

It provides a view builder for contact forms that displays the form.

It also results in contact messages being stored, among many other optional features. If you do not want that, then you can re-use the code from it for the view builder and add it yourself.

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


title: Example for creating Dropbutton

text:
# Question
Title: Example for creating Dropbutton
I really want to implement Dropbutton in Drupal8 But I can't find any concrete example for that.

```
$db = array(
        array('#type' => 'dropbutton', '#links' =>
           array(
            'a' => array('title' => t('Google'), 'url' =>  Url::fromUri('http://www.google.com')),
            'b' =>array('title' => t('Yahoo'), 'url' =>  Url::fromUri('http://www.yahoo.com')))
        )
 );

 $buf = drupal_render($db);

```

`$buf` will contain some dropbutton wrapper element in HTML but it doesn't get rendered as dropbutton in the page.

# Answer
When using a Dropbutton in a form, there is documentation on the class itself (since this question is over a year old, it may not have been there at the time) which matches the code above fairly closely (adjusted to match coding style would be something like):

```
$db = [
  '#type' => 'dropbutton',
  '#links' => [
    'a' => [
      'title' => $this->t('Google'),
      'url' =>  Url::fromUri('http://www.google.com'),
    ],
    'b' => [
       'title' => $this->t('Yahoo'),
       'url' =>  Url::fromUri('http://www.yahoo.com'),
    ],
  ],
];

```

This assumes that you're inside a controller or similar class that has access to the t() function. The comment above is correct, you do not need the wrapping array, and will cause trouble unless it is also a proper render array (useful when putting the button into a table or other nested structure).

It also worth noting the links are an array valid for `template_preprocess_links()` and not a render element for a link which allows for attaching AJAX call backs as needed.
> 2 votes

---
Tags: 8
---


# Question
Title: How to use Token Replace only if the field has a value?
So I've been using token replace for a while now with great success in my themes. For instance I'm using it currently to show the real name of an author by using

```
<?php print token_replace('[node:author:url]', array('node' => $node)); ?>">

```

The issue is that I've recently added a byline field in my storys and not all stories have a byline. I've added it normally by using

```
<?php print token_replace('[node:field_byline]', array('node' => $node)); ?>

```

However when the field is empty it simply prints \[node:field\_byline\] so I get stories like...

By: \[node:field\_byline\]

Is there a way to check that the token field has something in it and only show that field if there's a value? I'd like to just show nothing if there are now authors for the byline. I tried using something like:

```
<? !empty [node:field_byline] ?>

```

but this hasnt worked. Ideas?

# Answer
Figured it out! I just used the following and it worked fine.

```
<?php if (token_replace('[node:field_byline]', array('node' => $node))): ?> <?php print token_replace('[node:field_byline]', array('node' => $node)); ?> <?php endif ?>

```

If there is a better way to do it I'm all ears! – doodirock Jan 3 at 23:00
> 0 votes

# Answer
You can use the 'clear' option of token\_replace to clear any tokens it can't find a replacement for.

```
<?php print token_replace('[node:author:url]', array('node' => $node), array('clear' => TRUE,); ?>">

```

As documented here: https://api.drupal.org/api/drupal/includes%21token.inc/function/token\_replace/7.x
> 1 votes

# Answer
Maybe this could help?

```
<?php
   $pos = strpos(token_replace('[node:field_byline]', array('node' => $node)), 'node:');

   if ($pos !== false) { // field is not empty
      print token_replace('[node:field_byline]', array('node' => $node));
   }
   else {
      print '';
   }
?>

```
> 0 votes

---
Tags: entities, theming, tokens
---


title: Check if form already failed validation

text:
# Question
Title: Check if form already failed validation
I added a validation hook to a node creation form.

For my project, i need this validation only ONE time: basically i just check if a value already exists in the DB and i notify it to the user. If the user still submits the form, i must add it anyway.

i would like to do something like that:

```
if (form_did_not_fail_validation_before) {
  $form['#validate'][] = 'my_module_validation_hook';
}

```

in my hook\_form\_alter, so that validation hook is only called the first time.

I can't find a way to check if the form already failed validation, any ideas?

# Answer
> 0 votes
Two possible solutions: 1) set a session var in your validation script to flag when validation fails, then you can check if that session var is set (validation failed once) then add it anyway. 2) If you can't rely on session var, you can look at adding a custom boolean field to your user to flag this this user has failed validation once, then check if that field if true(failed once)/false(hasn't failed yet) and code accordingly, and you'd want to reset this field to false again once the node has been created in case you need to use it again for another node form.

# Answer
> 0 votes
You cannot add a conditional validator in hook\_form\_alter because the form will only be altered one time, while it is built.

What you could do, is add a custom validator function, and add a bool attribute to the $form.

Something like this in my\_module\_form\_alter:

```
$form['#validate'][] = 'my_module_form_validate_callback';
$form['#my_custom_validation_ran'] = FALSE;

```

Then create your validation function to only work the first time:

```
function my_module_form_validate_callback(&$form, &$form_state){
  if (!$form['#my_custom_validation_ran']) {

    ... logic ...

    $form['#my_custom_validation_ran'] = TRUE;
  }
}

```

---
Tags: 7, forms
---