title: Did the bootstrap process change?

text:
# Question
Title: Did the bootstrap process change?
I've had minimal experience with Drupal 7, and I am migrating over to Drupal 8.

I was curious as to what the flow of execution is when serving up a basic page in Drupal 8. In Drupal 7, this was considered the bootstrap process.

Is there an equivalent in Drupal 8?

# Answer
> 2 votes
The process is rather different. There are some common elements but maybe what can get confusing is how D8 leverages the Symfony Framework.

```
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);

```

As can be witnessed by the index.php, things look a bit different. But it is essentially "bootstrapping" functionality. To get a really good sense of what is going on, I would highly recommend reading the following:

https://cipix.nl/understanding-drupal-8-part-1-general-structure-framework

Also, the Drupal 8 Documentation helps to get a good grasp on what is available to work with:

https://www.drupal.org/docs/8/

Especially giving the API's a good looksy:

https://www.drupal.org/docs/8/api

As I said, it's quite different than before. A lot more OOP going on. It's quite powerful and gives developers a lot more tools to work with but if you aren't used to how PSR-0 and PSR-4 autoloading work, you might find it hard to debug and grock.

Good luck and Happy Drupalling!

---
Tags: 8
---


title: hook_menu_alter for taxonomy vocabulary

text:
# Question
Title: hook_menu_alter for taxonomy vocabulary
My vocabularies machine name is `vocab_ . $account_id` .
First Funcs: too see the user $account\_id is the same with vocab.. if yes then return TRUE.

```
function _term_account(){
  global $base_url;
  global $user;
  $account_id = custom_get_user_account_id();
  $tesr = explode('_', arg(3));
// admin/structure/taxonomy/vocab_21117 .. witch 21117 is $account_id
 if($tesr[1] == $account_id){
    return true;
 } else {
    return false;
 }
}

```

I use `hook_menu_alter` to alter the taxonomy url:

```
function custom_menu_alter(&$items) {
  // Works fine.. So every user has he's own and only vocabulary..
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list']['access callback'] = '_term_account';
  // DOESN'T WORK.
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add']['access callback'] = '_term_account';
}

```

**UPDATE**
When User edit term..

```
function _term_account_edit(){
    $account_id = custom_get_user_account_id();
    global $base_url;
    $term = taxonomy_term_load(arg(2));
    if($term->vocabulary_machine_name == 'branches_'.$account_id){
        return true;
    }else{
        return false;
    }
}

function custom_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term/edit']['access callback'] = '_term_account_edit';
}

```

The `Delete` Button dosen't Show up? Why?

# Answer
> 0 votes
I fix it .. Just disable **taxonomy\_access\_fix** module cause it has the same menu alter with access callback ..

# Answer
> 1 votes
The code looks good! However, try the following:

* See if there is already a permission or a module which lets you control the things you wish to control. Maybe you can mention the desired outcome or the objective in the question?
* Add a `dpm()` or something to the end of the function to see if the `$items` are being modified correctly.
* Add a `dpm()` or something in the `_term_account()` function to see if it is being called correctly and that it is returning `TRUE` or `FALSE` correctly as per your requirements.

---
Tags: 7, taxonomy-terms, routes
---


title: Quicktabs not looking like tabs

text:
# Question
Title: Quicktabs not looking like tabs
I use quicktabs on D8. When choosing the formater "quicktabs" the tabs do not look like tabs at all, they are just shown as normal links. They have no outlines and so are hardly recognizable as tabs at all. Should they not look like the "normal drupal tabs"? (When I choose to show the tab title, it is also not formated, just plain text, I guess it should be formatted as a header?)

I tried different themes, does not make a change, of course the site looks different, but the tabs still have no outlines. Currently I use Bootstrap default theme.

I am quite new to drupal, just building the site structures now, not having any idea of theming yet. I was already searching a lot, no clues, and all pictures I find of quicktabs on D8 look like tabs, not like the "linklist" I see.

Any hints appreciated :) I am absolutely willing to read / learn more, so if anyone could tell me, where to find more information, that would be great!

(EDIT) Looks like Quicktabs in D8 are causing several problems. Suddenly all context filters are no longer working for views inside quicktabs (they are working fine outside). And when I add a new quicktabs instance I have to clear the cache to make it show as an available block in the block layout page. Looks like I have to find a layout without tabs... :/

Is anyone using Quicktabs in D8 working as expected?

# Answer
Did you try changing tab style? I haven't tried Drupal 8. But you can select no style option in tab style for Drupal 7. Which does not apply any CSS to tabs.
> 0 votes

---
Tags: theming
---


# Question
Title: drupal commerce conditional checkout panes
I have used the following module to add a custom checkout pane to get some additional information from the user regarding the order.

https://drupal.org/project/commerce\_fieldgroup\_panes

I now need to apply a condition that if the order contain a product of specific product type then display this pane else hide it.

Can some one please guide me how can I do this.

I have found the following code from https://drupal.org/node/1807092 but I don't know how to modify it according my need. Looking for some help on how to modify & use this code.

```
<?php function commerce_conditional_panes_commerce_checkout_pane_info_alter(&$checkout_panes, $form, &$form_state) {
global $user;
foreach($checkout_panes as $pane_name => &$pane_data) {
    // load current order
    $order = commerce_cart_order_load($user->uid);
    // retrieve the value of controlling field
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $control = $order->field_make['und']['0']['value'];
    // Perform switch to see what to do with each aircraft make
    switch ($control)
    {
       case "value1":
         break;
       case "value2":
         break;
       case "value3":
         break;
       case "value4":
         break;
       case "value5":
         break;
       case "value6":
         // ...we only need to override one of them
         if($pane_name == 'commerce_fieldgroup_pane__conditional_pane' && $pane_data['enabled']) {
           // the pane is enabled by default, so we need to disable it
           $pane_data['enabled'] = 0;
         }
         break;
       case "value6":
         break;
       case "value7":
         break;
       case "value8":
         break;
       default:
         break;
       }
    }
}
?>

```

# Answer
It's surely too late for your project... Anyway, you may use Commerce Rules Extra, it adds the exact features you need :

> * Rules conditions : Total product of type quantity comparison : Total of products of specified type and with a specified quantity
> * Rules actions : Change pane properties : Change visibility, page, weight of a pane

Once you installed it, in checkout settings , set your pane as disabled by default and create a new rule

* event: Process checkout pane
* conditions: Total product of type quantity comparison
    + Parameter: Order: \[commerce\_order\]
    + Product Type: YOUR PRODUCT TYPE
    + Operator: \>, Quantity: 0
* action : Change pane properties
    + Parameter: Id of pane to change: YOUR PANE
    + Enabled: true
    + move to : checkout
> 7 votes

# Answer
Kojo's answer will no longer work as the 'Commerce Rules Extra' no longer can be used to hide panes.

See: https://www.drupal.org/node/2083981#comment-9740753

"Looks like hook\_commerce\_order\_view\_alter doesn't exist anymore, you are right" - Perignon (module maintainer)
> 0 votes

---
Tags: 7, rules, commerce
---


title: GMap Activation Error

text:
# Question
Title: GMap Activation Error
I have run into an odd error with my gmap module where I allow users to use the map to choose the location (rather than enter coordinates, they are allowed to enter an address too of course) but back to the map.

What's off is that the map 'works' it's just that it starts off greyed out, but if you double click the map it pops up as normal (Google Streets). Has anyone run across this error before?

----- Edit-----

It appears that if you open up the page and the map is greyed out, if you adjust the size of the browser window even the slightest, the map will appear as normal. So where could this problem be originating from?

# Answer
This is a classic GMap problem. It usually occurs when the map doesn't know it's dimensions initially. For example: when the dimensions are set in a stylesheet (`.gmap {width: x; height: y;}`).

You could try setting them inline on the wrapper div (`<div class="gmap" style="width: x; height: y;">`) or trigger a resize after the page has loaded, as explained here: How do I resize a Google Map with JavaScript after it has loaded?

If you are using the gmap or geolocation module, you can set the dimensions in the widget properties.
> 0 votes

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


# Question
Title: Views filters on exposed block - Not working initially
I have a view with exposed filters "status" already set default to "ready". The view filters are exposed in a block.

When I first open the view page, the status "ready" is ignored and it only applies the filter when I click on the "Submit" button in the exposed form.

I want the status "ready" to be applied when I open the view page. This works great if the filters are not in an exposed block... but I need them to be...

What can I do?

# Answer
Download and enable Better Exposed Filters. You should find a new setting under Exposed Form, in BEF Settings check "Autosubmit" and that might solve your problem.
> 0 votes

---
Tags: views
---


# Question
Title: "Posting date" format cannot be localized
**Website:** http://grausig.info
**Drupal version:** 8.3.5
**PHP:** 5.6
**Theme:** Bartik
**Language:** only German language installed (to avoid /de/ in URLs)
**Modules:** only "Tayonomy menu" and "Markdown filter"
**Installation:** early of 2017 from scratch
**Cache rebuild:** "drush cr" used all the time after having changed something

I cannot change the Drupal 8 posting date format of articles and book pages into a German format (day before month). It seems to use the "Default medium date". The posting dates at the abstracts on the starting page remain always English (month before day):
http://beginnersmind.de/pics/scrshots/FrontPage.png

But I already changed "Default medium date" into German style such that day comes before month. admin/config/regional/date-time/formats/manage/medium looks good: http://beginnersmind.de/pics/scrshots/DefaultMediumDate.png

**But:** admin/config/regional/date-time always shows the wrong date pattern by ignoring the modification: http://beginnersmind.de/pics/scrshots/DateAndTime.png
"drush cr" does not help. I always get month before day.

**Update:** I was able to verify this behaviour with a clean new and empty Drupal 8.3.5 install! Without having the German language installed I am able to edit the English date format. admin/config/regional/date-time shows the configured patterns. However, after having installed and activated German it is not possible to change the date-time format any more. The name of the day turns into German, but the date pattern does no longer reflect the configured state.

**Note:** The meaning of the date 07/10/2017 depends on the language:
\- English: July 10, 2017
\- German: Oct 7, 2017
So it is confusing for readers if an English date format is applied to a German text.

**Questions:**

1. Did I miss any necessary config action?
2. Is this a bug?

# Answer
I assume this is a bug since the behaviour occurs also at a fresh Drupal installation without any content. A bug report was filed. It contains a step-by-step instruction to reproduce the problem.

**Workarounds for mono-lingual sites where the English date pattern won't fit:**

* Modifying twig files which obviously means sub-theming. I am not shure whether this works on non-English sites
* Leaving the Language module inactive. Date patterns remain editable with the frontend. But e.g. to translate the "submitted by" of posting dates one has to modify node.html.twig which again means subtheming. This works for me.

**Edit Oct 11, 2017:** The best workaround for non-English monolingual sites known to me and tested by me is: Directly install the target language! Never install English or you may be lost! This can be done with the language selection menu during web install after having loaded the Dupal code. I proceeded as follows to install Drupal 8.4:

* In the shell: Go to the webroot directory.
* In the shell: drush dl drupal --drupal-project-rename=directoryname
* In the shell: cd ./directoryname
* In the shell: composer install
* In the browser: call the URL of the site
* In the browser: follow install instructions and choose your language

*Note:* As a result the core modules "Configuration Translation" and "Content Translation" were **not** enabled but "Interface Translation" and "Language" were enabled. It is now *possible to edit the date and time patterns*.

*Note 2:* I do not recommend to use "drush site-install"!
> 0 votes

---
Tags: datetime
---


title: Custom REST Resource POST problem

text:
# Question
Title: Custom REST Resource POST problem
I want to POST json data to a custom REST resource. I tested with postman and Insomnia but i get the message as if would've done a GET request and returns the get functions result. The GET function works fine btw.

In the logs it says "Switched from post to get".

I just want to return the data the user passes. This is the code of my custom REST resource:

```
<?php
namespace Drupal\foolzz_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides User Profile REST Resource
 *
 * @RestResource(
 *   id = "profile_resource",
 *   label = @Translation("Profile resource"),
 *   uri_paths = {
 *     "canonical" = "/foolzz_rest_api/profile/{uid}"
 *   }
 * )
 */
class ProfileResource extends ResourceBase
{
    /**
     * Responds to entity GET requests.
     * @return \Drupal\rest\ResourceResponse
     */
    public function get($uid = NULL)
    {
        $query = \Drupal::database()->select('foolzz_users_profile', 'data');
        $query->fields('data', array('fk_users_uid','status','displayname','birthdate','biography','gender','realname'));
        $query->condition('data.fk_users_uid', $uid);

        $profile = $query->execute()->fetchAssoc();

        $response = ['profile' => $profile
        ];

        $build = array(
            '#cache' => array(
                'max-age' => 0,
            ),
        );

        return (new ResourceResponse($response))->addCacheableDependency($build);
    }

    /**
     * Responds to POST requests.
     * @return \Drupal\rest\ResourceResponse
     * Returns a list of bundles for specified entity.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function post(array $data = []) {

        $response = array(
            "data" => $data,
        );

        $build = array(
            '#cache' => array(
                'max-age' => 0,
            ),
        );

        return (new ResourceResponse($response))->addCacheableDependency($build);
    }
}

```

# Answer
> 8 votes
Looks like you've stumbled across the same stumbling block as I have a couple of times. Try with this piece of code - note the create entry after canonical:

```
 *   uri_paths = {
 *     "canonical" = "/foolzz_rest_api/profile/{uid}",
 *     "https://www.drupal.org/link-relations/create" = "/foolzz_rest_api/profile/{uid}"
 *   }
 * )

```

Read more at: https://www.drupal.org/node/2811757 and https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview

Oh and for the post request, I'd use `ModifiedResourceResponse` instead of fiddling with cache headers by hand (I learned about the existence of that from Drupal Core's `EntityResource`)

# Answer
> 4 votes
I believe the syntax for your uri\_paths annotation should be:

```
 *   uri_paths = {
 *     "canonical" = "/foolzz_rest_api/profile/{uid}"
 *     "https://www.drupal.org/link-relations/create" = "/foolzz_rest_api/profile"
 *   }

```

The {uid} is not needed on the second line as it is present in the canonical path.

---
Tags: 8
---


# Question
Title: Custom entity api admin UI overview table how to add extra columns and operations? Drupal 7
I've seen this: Custom entity operation links but it's for Drupal 8 and dealing with nodes whereas mine is a non-node type entity.

So how does one go about adding stuff to the row? I want to add custom operations and basically get control of it but I can't see where to start.

I've extended `EntityDefaultUIController` in the conventional way (like this). When you go the administrative UI we can debug and break in `entity.ui.inc` and see the following code snippets which seems to be where this gets invoked. But I've got a feeling that there's a quicker and easier way than adding extended versions of the already existing `EntityDefaultUIController` functions. But what holds the operations & additional column row information?

**entity.ui.inc**

*within `overviewTable(...)`* ...

```
foreach ($entities as $entity) {
  $rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);
}

```

... which leads us to the following function (same file)

```
protected function overviewTableRow($conditions, $id, $entity, $additional_cols = array()) {

```

and we get use of $additional\_cols in the 4th (0th + 3 in array speak) parameter but as you can see it's not passed as a parameter above so how do you go about getting this additional information added into the overviewTable?

```
    // Add in any passed additional cols.
    foreach ($additional_cols as $col) {
        $row[] = $col;
    }

```

# Answer
> 4 votes
I figured out how do do this, and it, of course, isn't terribly straightforward...

You're on the right track, you just need to override the EntityDefaultUIController::overviewTable function in your own custom class. I don't think there's an easier way (since you're looking for one).

So, copy the the implementation of overviewTable from EntityDefaultUIController (in entity/includes/entity.ui.inc in the Entity API module) into your custom ui controller class and look for the calls to:

```
$this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);

```

...and add the $additional\_cols parameter which should be an array populated with the extra data (which you can pull from the $entity object already populated in the foreach loop. So, do something like:

```
foreach ($entities as $entity) {
  $additional_cols = array($entity->someField, $entity->someOtherField);
  $rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity, $additional_cols);
}

```

In addition to that you'd have to add the associated headers into the render array at the end of the overviewTable function like so...

```
$additional_headers = array('some field', 'some other field');

$render = array(
  '#theme' => 'table',
  '#header' => $this->overviewTableHeaders($conditions, $rows, $additional_headers),
  '#rows' => $rows,
  '#empty' => t('None.'),
);

```

...my guess is that you already figured out this much, but to answer your question, no, I don't think that there's an easier way. I hope this helps you, or someone else. ...or if someone knows this easier way, let me know too... =)

# Answer
> 1 votes
If you want to accomplish this cleaner and with less code, override the overviewTableHeaders and overviewTableRow functions (instead of overviewTable) in your controller class.

```
class CustomEntityDefaultUIController extends EntityDefaultUIController {

    protected function overviewTableHeaders($conditions, $rows, $additional_header = array()) {
        $additional_header[] = t('My Custom Field');
        $additional_header[] = t('My Other Custom Field');
        return parent::overviewTableHeaders($conditions, $rows, $additional_header);
    }

    protected function overviewTableRow($conditions, $id, $entity, $additional_cols = array()) {
        $additional_cols[] = $entity->my_custom_field;
        $additional_cols[] = $entity->my_other_custom_field;
        return parent::overviewTableRow($conditions, $id, $entity, $additional_cols);
    }

}

```

---
Tags: entities
---


title: How do I apply Tokens to a View?

text:
# Question
Title: How do I apply Tokens to a View?
I have a list of car models from a database. I want to make a View that filters these by make, based on tokens. Eg for the token `[cars:make]`.

I already have the tokens setup, but would anyone know how to actually use these as filters in a View?

# Answer
it may be posible with a node view, not with tokens, with field values: contextual filter, nid from url, provide a default value, php code, like:

> $node = menu\_get\_object(); if ($node-\>type == 'cars') {
> $mynodefiield = node\_load($node-\>nid)-\>field\_car\_make\[und\]\[0\]\[target\_id\]; return $mynodefield; }

note: \[target\_id\] is if field is an entity reference (node or taxonomy);

that view will return only nodetype=cars, and your token \[cars:make\] that have the same value as field\_car\_make.

sorry, i do not know how to do it with tokens, i hope it helps.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Update a user field after commerce checkout
Im looking for a way to create a rule in drupal commerce that updates a user profile after checkout based on a line item purchased.

Example. User purchases bulk training hours as a product. The product has a field called hours which we set to a static number. Assume 10.

When the product is purchased, the hours should be added to the user profile which has a field called training hours. Whatever the current number of hours in the profile is should be added. Ie user has 5 hours remaining, pays for 10 more and now shows 15.

I cant figure out a good way to create this rule.

EDIT 2: So from reading some other posts I see tried to create a component that can be accessed during the loop. For testing purposes I have changed the rule to start when checkout is complete.

It picks up the products and it then loops through the line items but in the loop I still cannot figure out how to access the field called field\_coaching\_hours that is part of the product. For not during the loop it emails me each time it finds a line item so I can tell that its working.

I suspect that I need to add up all the field\_coaching\_hours using a variable and then somehow call a separate rule to add it to the user profile.

Main Rule:

```
{ "rules_update_coaching_hours" : {
"LABEL" : "Update Coaching Hours",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "commerce_order_contains_product_type" : {
      "commerce_order" : [ "commerce_order" ],
      "product_type" : { "value" : {
          "coaching" : "coaching",
          "consulting" : "consulting",
          "product" : "product"
        }
      },
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "current_line_item" : "Current line item" },
      "DO" : [
        { "component_rules_get_coaching_hours" : { "current_line_item" : [ "current_line_item" ] } }
      ]
    }
  }
]
}
}

```

component:

```
{ "rules_get_coaching_hours" : {
"LABEL" : "Get Coaching Hours",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : { "current_line_item" : { "label" : "Commerce Line Item", "type" : "commerce_line_item" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "current-line-item" ], "field" : "field_coaching_hours" } }
],
"DO" : [
  { "mimemail" : {
      "USING" : {
        "key" : "SENT",
        "to" : "myemail@email.com",
        "subject" : "Component Rule Run",
        "body" : "[current-line-item:commerce-product]",
        "plaintext" : "[current-line-item:commerce-product]"
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
]
}
}

```

# Answer
I did figure this out and its working. I had to use some extra code to expose the custom field but it does work.

The component is as follows, this extracts the coaching hours and sends it out to the main loop via a provider variable:

```
{ "rules_get_coaching_hours" : {
"LABEL" : "Get Coaching Hours",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : {
  "current_line_item" : { "label" : "Commerce Line Item", "type" : "commerce_line_item" },
  "included_coaching_hours" : {
    "label" : "Item Coaching Hours Included",
    "type" : "decimal",
    "parameter" : false
  }
},
"IF" : [
  { "data_is" : { "data" : [ "current-line-item:type" ], "value" : "product" } },
  { "data_is" : {
      "data" : [ "current-line-item:commerce-product:type" ],
      "op" : "IN",
      "value" : { "value" : {
          "coaching" : "coaching",
          "consulting" : "consulting",
          "product" : "product"
        }
      }
    }
  },
  { "entity_has_field" : {
      "entity" : [ "current-line-item:commerce-product" ],
      "field" : "field_coaching_hours"
    }
  },
  { "data_is" : {
      "data" : [ "current-line-item:commerce-product:field-coaching-hours" ],
      "op" : "\u003E",
      "value" : "0"
    }
  }
],
"DO" : [
  { "data_set" : {
      "data" : [ "included-coaching-hours" ],
      "value" : [ "current-line-item:commerce-product:field-coaching-hours" ]
    }
  }
],
"PROVIDES VARIABLES" : [ "included_coaching_hours" ]
}
}

```

The the main rule is as follows. It loops through the line items and sums up total number of hours. The last line then updates the custom field in the user record.

```
{ "rules_update_coaching_hours" : {
"LABEL" : "Update Coaching Hours",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_payment" ],
"ON" : { "commerce_payment_order_paid_in_full" : [] },
"IF" : [
  { "commerce_order_contains_product_type" : {
      "commerce_order" : [ "commerce_order" ],
      "product_type" : { "value" : {
          "coaching" : "coaching",
          "consulting" : "consulting",
          "product" : "product"
        }
      },
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "decimal", "value" : "0" },
      "PROVIDE" : { "variable_added" : { "total_coaching_hours" : "Total Coaching Hours" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "current_line_item" : "Current line item" },
      "DO" : [
        { "component_rules_get_coaching_hours" : {
            "USING" : { "current_line_item" : [ "current_line_item" ] },
            "PROVIDE" : { "included_coaching_hours" : { "included_coaching_hours" : "Item Coaching Hours Included" } }
          }
        },
        { "data_calc" : {
            "USING" : {
              "input_1" : [ "total-coaching-hours" ],
              "op" : "+",
              "input_2" : [ "included-coaching-hours" ]
            },
            "PROVIDE" : { "result" : { "coaching_result" : "Coaching Summation result" } }
          }
        },
        { "data_set" : { "data" : [ "total-coaching-hours" ], "value" : [ "coaching-result" ] } }
      ]
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "commerce-order:owner:field-coaching-hours" ],
        "op" : "+",
        "input_2" : [ "total-coaching-hours" ]
      },
      "PROVIDE" : { "result" : { "updated_hours" : "updated coaching hours" } }
    }
  },
  { "data_set" : {
      "data" : [ "commerce-order:owner:field-coaching-hours" ],
      "value" : [ "updated-hours" ]
    }
  }
]
}
}

```
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: How to speed up event confirmation email?
I recently setup a Drupal 8 instance to set up a special event website. I am allowing users to build inline contacts to register for an RNG event. Everything seems to be working: The users offer their email and username, and the contact is created; then, they register for the event and the registration is created. Twelve hours later, they get an email message setup using the Courier and Rules integration with RNG.

Is there a way to speed up the confirmation email? If I send an email from a user contact form on the same website, it sends it immediately. I imagine it is a Courier/Rules issue with how often the email queue is being processed, but I cannot figure out where that is configured.

# Answer
Courier message dispatch is all done in cron. Therefore, in order to speed up the delivery of messages, you should run cron as often as possible.

Personally I run it every 30 seconds, but every 1-5 minutes should be fine in most cases.

Disclaimer: I am the maintainer of both the RNG and the Courier modules.
> 1 votes

---
Tags: rng
---


# Question
Title: Is there a way to use a PowerPoint presentation in a node?
I've been spending a lot of time trying to find a solution to play a PowerPoint in a node. Converting the file to SWF won't work for me since I need this to also play on mobile. Third-party upload doesn't work either because more than one person will be using this, and we don't want to have any liability in sharing the files to public this needs to be private. This is also why Google docs don't work.

It is crazy that there is no module that will play a PPT on Drupal, being PPT so easy.

Please I need a light here. I'm not a pro in Drupal, and I only have access to the Drupal dashboard. I can't fix any PHP or files either.

# Answer
> 0 votes
Try using https://www.drupal.org/project/gdoc\_field and field on node to upload and display powerpoint presentation.

---
Tags: nodes
---


# Question
Title: Display content by specific groups of users
Is it possible to display content by a group of authors without using a group module? I like the group module, but it's much more complex and robust than what I need it for.

Synopsis: We need to build a page that will display blog posts by not one specific author but by a group of authors dynamically and preferably contextually. The authors will not have control over this page or interact with it in any way. There will be dozens of these groupings of authors. The page will also display a view block of biographies for the authors that can be linked to the author's Drupal profile.

Edit: screenshot of my contextual filter using the selected answer below; pastebin of exported view

# Answer
> 2 votes
The simple solution would be to add **Term Reference** field to the user's profile fields. Then for each user assigned them a taxonomy (in this case the taxonomy term name would be the group name).

Use Field Permissions module to control who can edit and change the user's tax reference field.

Use Views and filter by taxonomy term to display the "group's" content. You will need to make a View of Users then under Advanced (far right) add a Relationship of Content authored.

# Answer
> 1 votes
You can also create a new user role and assign it to these specific authors then in your view:

1. Add relation to author.
2. Filter results where the user has this new role.

---
Tags: 7, views, blocks, organic-groups, group
---


# Question
Title: How can I use loop functionality in twig template?
I want to use a looping functionality in `region.html.twig` file to I can wrap elements (Blocks in this case) that outputted from `{{ content }}` section.

Defult `region.html.twig`

```
{% if content %}
  <div class="Parent">
    {{ content }}
  </div>
{% endif %}

```

The schematic generated Output:

```
<div class="Parent">
  Item_1
  Item_2
  Item_3
</div>

```

I try to use below code to create a loop and add a wrapper around of each `Item` outputted from `{{ content }}`:

My code:

```
{% if content %}
  <div class="Parent">
    {% for item in items %}
      <div class="child-wrapper">{{ item.content }}</div>
    {% endfor %}
  </div>
{% endif %}

```

The Final outpute that I want to achive:

```
<div class="Parent">
  <div class="child-wrapper">Item_1</div>
  <div class="child-wrapper">Item_2</div>
  <div class="child-wrapper">Item_3</div>
</div>

```

# Answer
> 0 votes
This should be like

```
{% if content %}
  <div class="Parent">
    {% for items in item %}
      <div class="child-wrapper">{{ item.content }}</div>
    {% endfor %}
  </div>
{% endif %}

```

items should come first if it has data in that. And remaining everything is correct.

# Answer
> 0 votes
I guess, you should look for items inside content.

```
{% if content %}
  <div class="Parent">
    {% for item in content %}
      <div class="child-wrapper">{{ item }}</div>
    {% endfor %}
  </div>
{% endif %}

```

I hope this works for you.

---
Tags: 8, theming
---


title: Drupal 8 page template for view page

text:
# Question
Title: Drupal 8 page template for view page
I know it should be very simple, I know it was working in Drupal 7 but I can't make it work in 8.

I tried this but it is not working. "page--path.html.twig" is not used, Drupal is using the "page.html.twig" template. The page I'm trying to theme is "example.com/path" . This page is just a view page. I'm not interested in theming the view, just the page markup around it.

# Answer
> 0 votes
Since its an alias,

For Drupal 8

In your THEME\_NAME.theme file:

```
function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Checks for node pages.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $current_path = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $alias = ltrim('/', $alias);
    $clean_alias = str_replace('/', '__', $alias);
    $suggestions[] = 'page__'.$clean_alias;
  }
}

```

You would like to check out clive answer from here for drupal 7

Template file naming with alias

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


title: D7 - hook_menu causes page duplicates

text:
# Question
Title: D7 - hook_menu causes page duplicates
I want to create a page that render a template (.tpl) file with this:

hook\_menu

```
    $items['news'] = array(
    'title callback' => 'check_plain',
    'title arguments' => array('News'),
    'page callback' => 'theme',
    'page arguments' => array('news', array()),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);

```

hook theme

```
$items['news'] = array(
    'template' => 'templates/news',
);

```

All works well if i go to www.mydomain/news

But if i go to www.mydomain/news/aaaaa (that is a non existing page) i will see again the template page and not a 404 error page, why?

Is this a normal d7 behaviors and i need to fix this in a callback function? ...or i need to check into other code/modules that cause this bug ?

# Answer
Yes, that's expected behaviour. From the `hook_menu()` docs:

> If there is no other registered path that fits the requested path better, any further path components are passed to the callback function.

Here's the bug report that was closed as "works as designed":

https://www.drupal.org/node/1091068
> 2 votes

# Answer
You can use a wildcard in your hook menu item like this: `$items['news/%']`. But why you are using theme function as a page callback? How do you handle loading news?

Please review this link: create .tpl file for a single custom page then you can load your news by EntityFieldQuery.
> 0 votes

---
Tags: hooks, theming
---


# Question
Title: Multisite - Commerce reference between sites
## Setup

Main website: www.example.com
LMS website: lms.example.com

* The Main website is public facing for visitors to browse the courses.
* The LMS website is for the users/commerce to be managed and the actual Course material to be used/viewed.
Drupal Commerce manages the payments and Access modules manage the users access once purchased.

The 2 websites are setup as Drupal multi-sites:

* On the same server
* Separate databases
* All modules/theme files are under the sites/all folder.

## Question

How do I create a 'Buy' button on the main website that will take the visitor to the LMS website with that particular course added in their cart?

Note: there is only a hand full of courses so the link on the main website can be manually added for each course.

# Answer
So I have discovered that I will need to create a Rule using the module Rules URL Argument that will take the URL /add-to-cart/\[SKU\] and add this to cart.

I can create a field on the main site for the SKU and this then outputs the link to the LMS website.

The source is here: https://www.youtube.com/watch?v=6Rn7FLFytTU
> 1 votes

---
Tags: commerce, multi-sites
---


# Question
Title: How do I get only one result using db_query()
I am transitioning from 'old school' PHP MySQL methods of using `mysql_fetch_array()`, etc. and I am trying to be more Drupally by using the Database API in my modules.

I simply want to return and print out a value. For example:

```
$query = db_query("SELECT zip FROM {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city));

```

I know the value is there, I can access and print it by using traditional methods outside the database API.

`print $query->zip` is not working.

The API documentation is as clear as mud.

Can someone tell me the correct way to access these values?

Is there a good tutorial anyone could recommend as well?

# Answer
> 40 votes
If you wish to fetch only one result you could use fetchField with `db_query` to fetch the result, e.g.:

```
$zip_code = db_query("SELECT zip from {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city))->fetchField();

```

You could also fetch the values retrieved from the query's returned result source using options like fetchObject() similar to methods of conventional PHP (`mysql_fetch_object`) coding like using and get results.

# Answer
> 16 votes
Here's how to use the Database API in Drupal 7 without writing a MySQL query:

```
$query = db_select('zipcodes', 'z')
  ->fields('z', array('zip'))
  ->condition('z.city', $city)
  ->range(0, 1)
  ->execute();
$result = $query->fetchObject();
print $result->zip;

```

# Answer
> 10 votes
You have to loop your $query, you can't suppose you only have one result with the above given query.

```
foreach ($query as $row) {
  print $row->zip;
}

```

If you know you only have one result, you could call fetchObject on your query -\>

```
$query = db_query("select zip from {zipcodes} where city = :city limit 1", array(":city" => $city))->fetchObject();

```

print $query-\>zip should then give you what you want.

# Answer
> 5 votes
I know this is old, but you can and should do:

```
$zip_code = db_select('zipcodes', 'z')
    ->fields('z', array(
        'zip'
    ))
    ->condition('city', $city)
    ->range(0, 1)
    ->execute()
    ->fetchField();

```

# Answer
> 3 votes
I would do

```
$row = (object)db_query('Your SQL here')->fetchAssoc();

```

if you want exactly one row from result set. Otherwise looping with foreach is the best option, as suggested before.

# Answer
> 0 votes
Well you have to ways to do this properly in Drupa 7:

1. db\_select - in Drupal there is a function that return an object that you construct with him the SQL query - https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db\_select/7. You have a method on the object called range. you can use it.
2. Entity field query which is a class that construct a SQL query upon entites: https://www.drupal.org/node/1343708. This is also have the range method.

# Answer
> 0 votes
**Drupal 7**

Use This Query For Single result:

```
$zip_code = db_query("SELECT zip from {zipcodes} WHERE city = :city", array(":city" => $city))->fetchField();

```

Instead of using this

```
$zip_code = db_query("SELECT zip from {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city))->fetchField();

```

because its generate warning.

# Answer
> -2 votes
**Drupal 6**

`$query` will be your result You need to fetch values from it, In your case If it fetches only 1 row and 1 column i.e zip then to get directly

```
$zip = db_result(db_query("YOUR SQL QUERY"));

```

`$query->zip` will not work as $query is result set not a loaded object or an array. So this should do

```
while($row = db_fetch_object($res)){
  $row->zip ; // etc
}

```

Note: `db_fetch_array` is another API to fetch values in array format

---
Tags: 7, database
---


# Question
Title: How do I implement hook_views_query_alter()?
I try to implement `hook_views_query_alter()` in Drupal 8. I found a hint, that it has to be in my\_module.views\_execution.inc. I tried it, but the hook never gets called.

```
function mymodulename_views_query_alter(&$view, &$query)
{
    var_dump('foo');die;
}

```

Do I have to register the \*.inc file anywhere? Do you have a documentation source on this topic?

# Answer
> 4 votes
Hooks need to be implemented in the .module file.

Just move the hook to your .module file, rebuild the cache, and Drupal will pick it up.

You could of course `require` a file that contains your hooks, as long as when that file is parsed, the hook functions are available in it.

You can read a bit more about hooks in the docs.

# Answer
> 8 votes
In Drupal 8, best practice is to use `hook_views_query_alter()` in `MYMODULE.views_execution.inc` file. If instead it is placed in `MYMODULE.views.inc`, it will be executed only when rebuilding the views cache, causing your view to function properly once and then not subsequently.

`MYMODULE.views_execution.inc` file should have this structure...

```
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 */
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  // Only for my_view view.
  if ($view->id() == 'my_view') {
    // some action
  }

}

```

Ref: `views_test_data.views_execution.inc`

# Answer
> 3 votes
creating hook\_views\_query\_alter in d8 is not same as d7, ofcourse.. after many try, i managed to get this one.. hope this helps.. its for different GET parameter ..

```
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ( ($view->id() ==  'MY_VIEW' && $view->current_display == 'page_1')) {
  $allowed_filters = ['language'=>['table'=>'node__field_v_language','condition_field'=>'field_v_language_value','operator'=>'IN'],
    'country'=>['table'=>'node__field_v_country','condition_field'=>'field_v_country_value','operator'=>'IN'],
    'city'=>['table'=>'node__field_v_locations','condition_field'=>'field_v_locations_target_id','operator'=>'IN'],
    'theme'=>['table'=>'node__field_v_themes','condition_field'=>'field_v_themes_target_id','operator'=>'IN'],
    'tag'=>['table'=>'node__field_v_tags','condition_field'=>'field_v_tags_target_id','operator'=>'IN'],
    'chId'=>['table'=>'node__field_v_ch_id','condition_field'=>'field_v_ch_id_value','operator'=>'IN'],
    'publishedBefore'=>['table'=>'node__field_v_published','condition_field'=>'field_v_published_value','operator'=>'>'],
    'publishedAfter'=>['table'=>'node__field_v_published','condition_field'=>'field_v_published_value','operator'=>'$record){
      $alias = $q.'_als';
      $condition_field = $alias.'.'.$record['condition_field'];
      $configuration = [
        'type'       => 'LEFT',
        'table'      => $record['table'],
        'field'      => 'entity_id',
        'left_table' => 'node_field_data',
        'left_field' => 'nid',
        'operator'   => '=',
      ];

      $join = \Drupal\views\Views::pluginManager('join')
        ->createInstance('standard', $configuration);
      $rel = $query->addRelationship($alias, $join, 'node_field_data');
      $query->addTable('node__field_v_language', $rel, $join, $alias);
      $query->addWhere('', $condition_field, [$_GET[$q]], $record['operator']);
    }
  }
}

```

---
Tags: views, 8, hooks
---


# Question
Title: Show modal modal message on form success
I have a custom form that submits via AJAX. On form error, i simply return the whole form on my callback function, and the HTML is replaced, but i want it to open a modal dialog on success. What is the best way to do this? This is what i'm currently doing (i don't like this solution because i can't clear the form values, among other things):

```
    public function ajaxCallback(array &$form, FormStateInterface $form_state) {

        drupal_get_messages(); // Hide the status messages

        $form_state->setRebuild(TRUE);

        if ($errors = $form_state->getErrors()) {

          return $form;
        }
        else {

          $response = new AjaxResponse();

          $title = 'Consectetur adipiscing elit';
          $text  = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';

          $response->addCommand(new OpenModalDialogCommand($title, $text));

          return $response;
        }
      }

```

# Answer
Here is what i came up with (many thanks to @4k4):

```
    public function ajaxCallback(array &$form, FormStateInterface $form_state) {

        drupal_get_messages(); // Hide messages

        $form_state->setRebuild(TRUE);

        if ($errors = $form_state->getErrors()) {

           return $form; // Simply Return the form
        }
        else {

         $response = new AjaxResponse();

         $title = 'Consectetur adipiscing elit';
         $text  = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';

        $response->addCommand(new OpenModalDialogCommand($title, $text));

        // Or add the $form as parameter to an HTML command.
        $response->addCommand(new ReplaceCommand('#my-form-wrapper', $form));

        // Do notice i added a wrapper to my form in the buildForm() method:
        // $form['#prefix'] = '<div id="my-form-wrapper">';
        // $form['#suffix'] = '</div>';

         return $response;
    }

```
> 0 votes

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


# Question
Title: How can I filter sensitive data being recorded in calls to Watchdog
I have sensitive data that is sent to a Drupal instance and I don't want it to be logged. I can filter out sensitive values with simple string replacements for my own calls to `watchdog()`, but for PHP errors and other modules making `watchdog()` calls, the data may be logged and this needs to be filtered too.

# Answer
Assuming you're dealing with the dblog module, this is a workable solution:

1. Disable the dblog module
2. Copy `dblog_watchdog` into your own module's `hook_watchdog` implementation
3. Wrap each of the appropriate database field entries with your function to sanitise the string, e.g.

```
Database::getConnection('default', 'default')->insert('watchdog')
  ->fields(array(
    'uid' => $log_entry['uid'],
    'type' => mymodule_sanitise(drupal_substr($log_entry['type'], 0, 64)),
...

```

If you have other watchdog modules in use, you'll need a copy/edited `hook_watchdog` version for each of them too.
> 2 votes

---
Tags: 7, security, log-messages
---


# Question
Title: How to check if a menu exists programatically in Drupal 8
I have a script where I instantiate and fill menus with menu items programmatically.

Whats the best way to check if a menu already exists if I already know it's ID.

# Answer
A menu is a config entity, which means you can use standard entity API to load it.

\Drupal\system\Entity\Menu::load() or \Drupal:entityTypeManager()-\>getStorage('menu')-\>load()
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Display custom user profile field as name in articles
I would like to display the custom user profile field `name` as the author's name in articles, instead of the user's username. How can I do this without modifying code of my template or Drupal itself?

I saw solutions for Drupal 7 but I'm using Drupal 8. I found custom modules for Drupal 7 or earlier and code modification ways. Both seems wrong to me because the mentioned modules aren't updated nor it feels correctly to me to change code to achieve this quite basic task.

# Answer
You can use the Realname module to override the display name with the values of one or more fields:

> The RealName module allows the administrator to choose fields from the user profile that will be used to add a "real name" element (method) to a user object. Hook\_user is used to automatically add this to any user object that is loaded. It will also optionally set all nodes and comments to show this name.
> 0 votes

---
Tags: 8
---


# Question
Title: Hide flag field from certain nodes in view
I'm new to Drupal, so I may be missing some "obvious" things

I've installed the flag module, so users can flag their content to make it appear on top of other views. The thing is, when I display the list of content to the user (including both published and unpublished nodes), flag shouldn't be available if the node is unpublished

I tried to alter the view using the hook `hook_views_pre_render`, but I don't seem to have access to the flag content for removing (I guess my hook is being called after the flag hook, but I'm not certain about that). I tried this:

```
function mymodule_views_pre_render{
  switch ($view->name) {
    case 'usernodes':
      foreach ($view->result as &$row) {
        //Custom field with publish states, 3 means it is published
        if ($row->field_publish_state[0]['raw']['value'] !== '3') {
          //Unset the two values related to flags I could find
          unset($row->flagging_node_entity_id);
          unset($row->flagging_nodeuidisnotnull);
        }
      }
      break;
  }
}

```

But the flags are still rendered

What I think could work:

* I could use the hook `hook_views_post_render`, and edit the second parameter (`$output`) but it feels wrong to actually override the HTML output (it would become a messy code)
* I could change it using some Javascript, when the page loads, but it doesn't feel right
* Using Views PHP and then inserting a Global PHP field (as noted by code.rider below), but users have access to views and they could make a mess with that field

What would be the best way to hide the flag field for certain rows?

# Answer
* Install the Views PHP module and enable it. This will allow you to embed php into a view cell.
* Add a new nid/node id field to your View. Make sure to check the “Exclude from display” checkbox.
* Add a new Content: Published field to your View. Make sure to check the
“Exclude from display” checkbox.
* Rearrange your fields so that your hidden nid field and published field at the top of all fields. This is important. It needs to be “available” as an element to the custom php field we are about to add, and if it’s after, the custom php field won’t see it.
* Add a new Global: PHP field.
* add the following code to the Output Code section of the field (in php):
```
if ($row->status) {
  print flag_create_link("the_machine_name_of_your_flag", $row->nid);
}
```

```
 Use  delimiters to enclose PHP code.
```
* Click the apply button

use flag field in Sort criteria for sorting content mean flagged content on top
this is a tested solution.
hope this solve your problem.
> 1 votes

---
Tags: 7, nodes, hooks, flags
---


title: How to configure RDF on fields?

text:
# Question
Title: How to configure RDF on fields?
I have a type of recipe content and I would like google to display additional information in its results.

There is a built-in module to Drupal 8 "RDF" but I can not find anything to configure it on my fields.

How does it work ?

# Answer
> 1 votes
The Drupal built in RDF module works automatically and cannot be directly influenced from the user interface. There is however the Schema.org configuration tool (RDF UI) module.

> The module enables you to specify mappings between content types and fields with types and properties of Schema.org and build Content types based on schema.org. Through the rdf module, specified mappings will be embedded in HTML as RDFa, to provide semantically rich data.

The video on the module page explains the process quite well.

---
Tags: 8
---


# Question
Title: How do I delete an old node when a new node is created?
When a user submits a new node, I want the Rules module to look for other nodes with the same email field, then delete the older node and keep the new node.

When a user adds a new node, there is an email field that always stays the same which can be used as field to find nodes.

Is there any way to do this?

# Answer
> 1 votes
with views rules is possible, a bit complicated, make a user view, you will need a contextual filter, "When the filter value is NOT available", "Provide default value", php code, then add something like:

```
global $user; // gets current logged in user object

 if (isset($user->field_user_address[LANGUAGE_NONE][0]['country'])) {
  $user_country = $user->field_user_address[LANGUAGE_NONE][0]
['country'];
return $user_country;}

```

instead of using & returning $user\_country, use & return your email field, and that view will return only the loggedin user field-email, add a relationship on node author, then add "node title" or whatever form the relationship, then apply a rule on that view and delete (or unplubish) that content. hope it helps.

EDIT: may be is over-coded my solution, just add a user view, contextual filter, loggedin user from URL, apply filters and relationships as needed to only get the node you are looking for, then apply a rule on that view.

# Answer
> 1 votes
A possible answer to your question is to use the Views Rules module, as further detailed below.

### 1. About the Views Rules module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

> ... provides two types of elements in Rules, configured with a "Rules" view display:
>
> * **Views loop**: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.
> * **Collect view result rows (action)**: This action collects each variable in all view result rows into list variables for use in Rules.
>
> ***Tip***: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

### 2. Create a view of display type 'Rules'

After you enable the Views Rules module, you can use Views to create a view of those "*other nodes with the same email field*" (as in your question). Add of view of display type ***`Rules`*** (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

### 3. Create a rule using the view of display type 'Rules'

Create an appropriate Rule, using these guidelines:

* Rules Event: after creating a new node (possibly limited to selected content types only).
* Rules Conditions: add whatever may fit for your case (eg: limit to node authors of selected user roles only).
* Rules Actions:

+ Use the link that says `Add view loop` to add a Views loop, and select the "Rules" display created in the previous step.
    + Configure the parameters and variable names.
    + For each node contained in your Views loop, perform whatever Rules Action that fits your requirement, using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). You probably want some rules Action like "delete the node".

***Easy, no?***

---
Tags: 7, rules
---


# Question
Title: Combine all nodes of two content types as table rows / columns
I have two content types: *Ingredients* (Butter, Flour, ...) and *Units of mesure* (Cup, Tablespoon, ...).

*Ingredients* have *Density* field (e.g *Flour, 0.53g/ml*) and *Units of mesure* a *Capacity* field (e.g. *Cup, 250ml*).

Using views, I am stuck trying to create a table similar to:

```
==================================================
|               | Nodes of "Units of measure"    |
|------------------------------------------------|
| Nodes of      | Math calculation based on      |
| "Ingredients" | "Desnsity" and "Capacity" values
|               |                                |
|               |                                |
==================================================

```

For example:

```
==================================================
|         | Grams | Cup  | Tablespoon | Teaspoon |
|------------------------------------------------|
| Butter  | 100   | 0.44 | 7.05       | 21.16    |
| Flour   | 100   | 0.80 | 12.80      | 38.43    |
| ...     |       |      |            |          |
|                                                |
==================================================

```

I don't know how to generate such a table with two content types titles as rows and columns respectively.

Any help would be appreciated. Thanks!

**EDIT:**

* I read about similar questions that use references and relationships, but this view should show **all** nodes of both content types. So, they don't need to be related.
* Maybe *Units of measure* should be a Taxonomy instead of a content type? I am open to answers changing the scenario/context described. How would you create such a table with Drupal?

# Answer
its very easy if contentypes are "entity reference" related, on "less important" contentype add an entityreference field and relate that node to "main contentype", in views add a relationship with your entityreference field, filter (not exposed) to display only "main contentype", and when adding fields to your view (now both contentypes fields are listed in drop menu field listings), specify if you use or not the relationship, for fields on "main contentype" do not use relationship, do it in all "less important contentype" fields. done.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: Is it possible to restrict the number of published items for a given content type?
I have a content type called "tile" that I'd like for there to only be 6 of published at any given point, so that the page they're on doesn't get too cluttered.

Is there a way to enact this restriction in a way that won't confuse the user?

Edit/For Clarification: It's alright if there are more pieces of content that exist that are unpublished, but I'd like for only 6 of them to be published at any given time.

# Answer
> 1 votes
The easiest way I can think of is pulling those tiles in as a view - limit it to the 6 most recently submitted tiles, and add a notice within the /node/add form to inform the user that creating a new tile will replace the oldest tile.

You could also add an extra field as a "Tile Display" - either a boolean (so an editor could go through and select the 6 they want to appear), or a number (set up a single-value number field, max value = 5, all must be unique. That way the user can go in and add a new tile, and if they want it to display first, they'd set the field to '0'; if '0' already exists, there will be a warning, and they'll have to go to the current 0-index tile to remove the value).

Your other option is to find some way to process the forms so that publishing a new tile forces the user to choose an old tile to un-publish - but that would be difficult to set up, and most likely confusing (at least for most content editors I've interacted with).

# Answer
> 1 votes
If this is a View, just limit the view and provide conditions (limit 6, must be published, sorted by new, etc).

The only enforced way I know to do this is with a Rule, or perhaps some other method of intercepting node/add/\* route, counting the existing entities, and blocking access with "you have created the maximum" sort of message. IMO this really sucks for the end user, and is better managed through Views conditions.

---
Tags: nodes
---


# Question
Title: Can A View Load All Data, And Filter (Hide) With CSS?
When using an exposed filter in a view, any data that doesn't meet the filter is removed from the page. Partially for SEO reasons, I'd like all the data to load (and stay in the HTML), but then the exposed filters will simply use CSS to hide the data that doesn't match the filter.

Does that make sense? Is it possible?

# Answer
I created a rather complicated arrangement of views inside of views. I was already using a Bootstrap child theme, so I used Pills and Data-Toggles (http://getbootstrap.com/javascript/#tabs). Global text areas (and some custom template markup) allowed me to create the markup that Bootstrap wanted. I'm sure there's a smarter and better "Drupal way", but this got me exactly what I wanted using already available Bootstrap code.

Thanks everyone for your help ;-)
> 0 votes

# Answer
### A module might be able to help you with this

https://drupal.org/project/mixitup\_views (drupal 7 + 8) Loads all items and might be close to what you need

https://www.drupal.org/project/isotope (drupal 7 + 8) A highly customizable module that is probably harder to implement as well

### Some other alternative modules

https://www.drupal.org/project/views\_semantic\_tabs (drupal 8) might be a good fit

https://drupal.org/project/shuffle (drupal 8) Not sure if it loads all results at once but it offers the filtering you described

https://drupal.org/project/views\_quicksand (drupal 7) does not load all results at once by has the filtering effect that you need so it might be a starting point

**NOTE:** all or almost all above module use JS libraries that you have to pay for if you implement them in commercial products

### A custom alternative

Create a view that displays all results and use global text area to rewrite all the elements to be part of a container div and add classes to the container based on the categories you want filterable

Then use this code https://codepen.io/terf/post/jquery-filter-divs in your custom module or theme changing `box` class with your container's class name
> 0 votes

---
Tags: views
---


# Question
Title: Class not dynamically loaded in custom module
I have a very simple Drupal 7 module in which I want to load a custom class. I'm not able to load the class and I get the following error when I enable the module:

```
Fatal error: Class 'Drupal\testmodule\TestClass' not found in www/sites/all/modules/testmodule/testmodule.module on line 4

```

Here are the contents of my module files:

**testmodule.info**

```
name = "Test Module"
core = 7.x
files[] = src/TestClass.php

```

**testmodule.module**

```
<?php

function testmodule_init() {
  Drupal\testmodule\TestClass::go();
}

```

**src/TestClass.php**

```
<?php

namespace Drupal\testmodule;

class TestClass {
  function go() {
    print 'Foo!';
  }
}

```

Please could anyone help me understand why Drupal 7's dynamic-loading code registry is not working as documented here: https://www.drupal.org/docs/7/creating-custom-modules/writing-module-info-files-drupal-7x#files ?

# Answer
> 2 votes
To use namespaced classes in Drupal 7, you can use one of these modules:

One reason for choosing one or the other may be if you have other modules that also depend on one of those modules.

Otherwise I guess it is largely a matter of taste.

One difference is that xautoload is more convenient during development, because newly created PSR-4 classes are immediately available without rebuilding the class registry.

On the other hand, it does a lot of things which you probably don't need right now, and the code looks complex.

Of course you could do some profiling to find out which is faster, but as always you would need to be careful what you measure and what you compare. I currently cannot tell you which one is faster, or better for memory.

There is also the alternatives module that can help to have only one of those enabled, instead of both.

*Disclaimer: I am the author of one of these modules, and I am subscribed to the autoload tag on drupal.stackexchange.com.*

# Answer
> 0 votes
I believe the reason is that Drupal 7's class loader doesn't account for namespaces, so it would find \TestClass but \Drupal\testmodule\TestClass is not found.

There are two ways around this: don't use namespaces (may not be possible), or include your own class loader as one of the files mentioned in your .info file.

There are examples of trivial autoloaders on this page: http://php.net/manual/en/language.oop5.autoload.php

---
Tags: 7
---


# Question
Title: How do I export Entityform submissions to CSV?
I see that it is possible to bulk download Entityform submissions to a CSV file.

How do I do it? I don't see a "Download as CSV" button anywhere.

# Answer
> 3 votes
My problem was that I installed Views Data Export *after* installing Entityforms.

I had to go to the Entityforms view (which is the automatically generated admin view showing the form's submissions), click the arrow next to "Edit View Name/Description" and click "Revert View".

Now a CSV/XML export button shows up on the Submissions view, and I can export happily.

---
Tags: 7, importing-exporting
---


# Question
Title: How to order by a column with NULL values in it due to leftJoin?
If you have two fields on a content type, such as "publications" and "featured publications" and you want to display a single list merging the two fields with the featured content on top.

I'm using two left joins from the base entity table, which leaves the delta non-featured items as NULL in the results set.

The problem I ran into is that orderBy on a delta column doesn't work with NULL values as NULL values will appear before any value with an integer in it.

So given a query like this:

```
$query = $this->database->select('publication_field_data', 'pfd')
      ->fields('pfd', ['id']);

    $query->leftJoin('node__field_publications', 'fp', 'fp.field_publications_target_id = pfd.id');
    $query->leftJoin('node__field_featured_publications', 'ffp', 'ffp.field_featured_publications_target_id = pfd.id');

    $query->orConditionGroup()
      ->condition('ffp.entity_id', $current_nid)
      ->condition('fp.entity_id ', $current_nid);
    // Sorting by deltas on the featured field, then the non-feature field
    // and then the non-featured field will fail, as the NULL values
    // on the featured field will appear first.
    $query->orderBy('ffp.delta');
    $query->orderBy('fp.delta');

```

You won't get the proper order.

So the question is, how can we fix the query so that it will order properly, first showing the featured items, then the non-featured items (and not showing duplicates).

As I'm using paging, you can just use two queries.

# Answer
> 3 votes
One solution I found is based on this response: https://stackoverflow.com/a/4326579/1214689

```
$query->addExpression('ffp.delta IS NULL', 'featured_delta_is_null');
$query->orderBy('featured_delta_is_null');
$query->orderBy('ffp.delta');
$query->orderBy('fp.delta');

```

Since sorting on the featured delta will place items with Null values at the top of the list, we need to sort featured delta in two pieces, first by those that aren't NULL (by converting to a boolean, those are lower than the ones that are NULL), then sort on the actual delta for those values that aren't null, this will leave all the other values out to be sorted by the delta on the non featured ('field\_publications') field.

---
Tags: 8, database
---


# Question
Title: How do I add a region to the Color module?
I have a menu I would like to be able to style with the Color module. I have found many examples for the Drupal 7 Color module and they have led me to believe that if I just add a line to the 'fields' array in the color.inc file in my theme I will be able to add more regions.

Below is my 'fields' array. I copied an existing file as a guide and simply added my primary menu

```
'fields' => array(
  'top' => t('Header background top'),
  'bottom' => t('Header background bottom'),
  'primarymenu' => t('Primary navigation menu'),
  'bg' => t('Main background'),
  'sidebar' => t('Sidebar background'),
  'sidebarborders' => t('Sidebar borders'),
  'footer' => t('Footer background'),
  'titleslogan' => t('Title and slogan'),
  'text' => t('Text color'),
  'link' => t('Link color'),
),

```

I just added the 'primarymenu' field to the standard bartik array

I realize there is more to do to connect this field to something so it will actually change colors but everything I can find is for D7 and requires altering php templates.

Why is my field not showing up in the appearance settings menu and how do I connect it to change the color of my menu?

Edited To add the schemes array

```
'schemes' => array(
'default' => array(
  'title' => t('Blue Lagoon (default)'),
  'colors' => array(
    'top' => '#055a8e',
    'bottom' => '#1d84c3',
            'primarymenu' => '#ffffff',
    'bg' => '#ffffff',
    'sidebar' => '#f6f6f2',
    'sidebarborders' => '#f9f9f9',
    'footer' => '#292929',
    'titleslogan' => '#fffeff',
    'text' => '#3b3b3b',
    'link' => '#0071B3',
  ),
),
'firehouse' => array(
  'title' => t('Firehouse'),
  'colors' => array(
    'top' => '#cd2d2d',
    'bottom' => '#d64e4e',
            'primarymenu' => '#ffffff',
    'bg' => '#ffffff',
    'sidebar' => '#f1f4f0',
    'sidebarborders' => '#ededed',
    'footer' => '#1f1d1c',
    'titleslogan' => '#fffeff',
    'text' => '#888888',
    'link' => '#d6121f',
  ),
),
'ice' => array(
  'title' => t('Ice'),
  'colors' => array(
    'top' => '#d0d0d0',
    'bottom' => '#c2c4c5',
            'primarymenu' => '#ffffff',
    'bg' => '#ffffff',
    'sidebar' => '#ffffff',
    'sidebarborders' => '#cccccc',
    'footer' => '#016b83',
    'titleslogan' => '#000000',
    'text' => '#4a4a4a',
    'link' => '#019dbf',
  ),
),
'plum' => array(
  'title' => t('Plum'),
  'colors' => array(
    'top' => '#4c1c58',
    'bottom' => '#593662',
            'primarymenu' => '#ffffff',
    'bg' => '#fffdf7',
    'sidebar' => '#edede7',
    'sidebarborders' => '#e7e7e7',
    'footer' => '#2c2c28',
    'titleslogan' => '#ffffff',
    'text' => '#301313',
    'link' => '#9d408d',
  ),
),
'slate' => array(
  'title' => t('Slate'),
  'colors' => array(
    'top' => '#4a4a4a',
    'bottom' => '#4e4e4e',
            'primarymenu' => '#ffffff',
    'bg' => '#ffffff',
    'sidebar' => '#ffffff',
    'sidebarborders' => '#d0d0d0',
    'footer' => '#161617',
    'titleslogan' => '#ffffff',
    'text' => '#3b3b3b',
    'link' => '#0073b6',
  ),
),

```

),

# Answer
You need to also provide a color for the field you added. In fact, the function that adds the form elements for the color settings contains the following code. (See `color_scheme_form()`.)

```
 foreach ($palette as $name => $value) {
    if (isset($names[$name])) {
      $form['palette'][$name] = array(
        '#type' => 'textfield',
        '#title' => $names[$name],
        '#value_callback' => 'color_palette_color_value',
        '#default_value' => $value,
        '#size' => 8,
        '#attributes' => array('dir' => LanguageInterface::DIRECTION_LTR),
      );
    }
  }

```

Without a color value for your field, `$form['palette'][$name]` will not be added, and it will not be possible to change the color for it.

In fact, the Bartik theme uses the following values, for its default palette.

```
$info['schemes']['default'] = array(
  'title' => t('Blue Lagoon (default)'),
  'colors' => array(
    'top' => '#055a8e',
    'bottom' => '#1d84c3',
    'bg' => '#ffffff',
    'sidebar' => '#f6f6f2',
    'sidebarborders' => '#f9f9f9',
    'footer' => '#292929',
    'titleslogan' => '#fffeff',
    'text' => '#3b3b3b',
    'link' => '#0071B3',
  ),
);

```

The keys you find in (for example) `$info['schemes']['default']['colors']` are the same keys you find in `$info['fields']`.
> 0 votes

# Answer
I experienced the same issue and after a lot of face-palming, I discovered why the new color field was not showing up.

In my case, I had already saved custom color settings for the original fields before adding my new field. Since the custom settings obviously didn't contain a value for my new field, it was excluded from display in the theme settings. Using the drop-down menu to change back to the default (or some other preset) color scheme solved the issue and then I was able to pick custom colors including the new field.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Where to write hook_commerce_payment_method_info() in drupal8?
I am migrating one of the drupal commerce related module from Drupal-7 to drupal-8.As I am newbie to D8, struggling to get proper structure in drupal-8. I have a hook that is `hook_commerce_payment_method_info()`. I am confused to where to write this hook. I am guessing it will be in `.module` file. please share your suggestions to me. So that I can move in right direction. Thanks in advance.

# Answer
> 2 votes
Payment methods are now called Payment gateways and they are plugins, like anything else.

So, look for the @CommercePaymentGateway annotation, like in this example: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/payment\_example/src/Plugin/Commerce/PaymentGateway/Onsite.php and the others in that folder.

---
Tags: 8, commerce, hooks
---


# Question
Title: Add to cart button enabled if subscriber seller
I want to create a marketplace. Each seller will be able to create a shop and products that will be displayed to all visitors.

* A non-subscriber (free) will have on his product a button "Add to cart" not clickable. The products can not be ordered.
* A subscriber (paid) will have on his product a button "Add to cart" clickable. The products can be ordered.

How to do this ?

How do I create subscriptions with an end date with drupal ?

# Answer
> 0 votes
My answer would be for Drupal 7 with respect to current code to your final question of functionality: \- After making sure both the rest of your structure is in place, Add the Rules watchdog that will "listen" for the role or lack thereof and then do not only 'it' but perhaps other things for example display a popup message. It would be possible to change the look or color of the button as well. Requirement: Rules module. Rules UI will have it write the code for you, that you can then save to code if you want. \- With a rule stating normal code behavior not having fired or reverting to normal behavior after logging in, then the button will do as it was coded to do.

Subscriptions with an end date in Drupal by marrying a subscription to a role by https://www.drupal.org/project/commerce\_license not released for 8 production yet whereby you do all the magic of billing: Commerce Billing is an option in Drupal 7, method, cycle, grace period, and expire or downgrade the role as you wish upon expiration. From a step point-of-view, this step precedes the rules, as this will be the basis for rules. "commerce\_billing" is only available for Drupal 7 at this time with respect to billing anyway, and the projects don't show a Drupal 8 version being started yet. That's why my answer is for Drupal 7 only at this time, except when one module may be ready but calls itself "dev", and the other is not yet started.

---
Tags: 8, commerce
---


# Question
Title: Exporting a feature to a specific directory using drush
I am creating a new feature using drush. I looked up the component I want to create the feature with. When I run the command `drush fe my_feature views_view:my_cool_view`, drush wants to put it in `sites/all/modules`. How do I tell drush to export my feature to `sites/all/modules/custom`?

# Answer
Use the command `drush fe my_feature views_view:my_cool_view --destination=sites/all/modules/custom`

https://drushcommands.com/drush-7x/features/features-export/ http://dirtystylus.com/2016/02/18/setting-a-destination-directory-for-drush-features-export/

Bonus: To change the name of the feature, and other info, edit the `name=` section of: `sites/all/modules/custom/my_feature/my_feature.info`
> 1 votes

---
Tags: 7, drush, features
---


# Question
Title: Print image field path in views-view-fields--key-projects.html.twig
I am working with Drupal 8 and trying to print some fields through a twig file.

Created:

1. A view (format:grid)
2. A content type (fields: title, body image)
3. Contents

File working on:

1. views-view-fields--\[machine-name\].html.twig

To Do:

1. How can I print the path of the image in the content?
2. How can I print the path of the node/content on a Read More link?

# Answer
> 0 votes
To get the path of an image in a view, use the image format 'URL to Image' in the field setup. I have not found a really good way to get the site absolute, rather than relative url, but prefixing the returned value in a rewrite block with `{{ url'(<front>') }}` is almost there:

```
{{ url'(<front>') }}{{ field_image }}

```

To use that in a different field (content), mark it 'Excluded from display' and then reference that field using a rewrite in another field, or using a twig field template.

# Answer
> 0 votes
Q: How can I print the path of the image in the content? A: I got the file path of image by printing the image field directly in twig. Like: {{ fields.field\_sliding\_image.content }}

Q: How can I print the path of the node/content on a Read More link? A: I added a path field in my view and then in twig I did the following: Like: {{ fields.path.content }}

---
Tags: views, theming, media
---


title: Get block title from hook block view

text:
# Question
Title: Get block title from hook block view
I create blog programmatically and I want to show title block.

This is not working:

```
  'header' =>  array(
                    '#prefix' => '<p>',
                    '#suffix' => '</p>',
                    '#markup' =>  $block->subject,
               ),

```

Or better to create new field via ***hook\_block\_configure***? Maybe exist way to find title from DB?

# Answer
> 0 votes
Try like this

```
 $block = module_invoke('views', 'block_view', 'name-block_1');
 $title = $block->title;
 $content = render($block['content']);

```

---
Tags: blocks, hooks
---


# Question
Title: Getting all the values from a entity reference field (Drupal 8)
I'm trying to figure how I can get all the values inside an entity reference field

As shown in this image, I have an entity field called Target Participants(field\_program\_participants) with multiple values.

I have tried to output the values using `node.field_program_participants.entity.label`, but it only outputs one value.

How can I output all the values inside the field

# Answer
You have to loop over the field items:

```
{% for item in node.field_reference %}
  {{ item.entity.label }}
{% endfor %}

```
> 1 votes

---
Tags: theming, entities
---


# Question
Title: hook_ENTITY_TYPE_view() only fires once on cache rebuild?
When implementing hook\_ENTITY\_TYPE\_view() for nodes, I notice the following behaviour:

* Cache rebuild
* Navigate to node/1 // Message 'Node viewed!' displays
* Navigate to node/2 // Message 'Node viewed!' displays
* Navigate to node/1 // No message
* Navigate to node/2 // No message
* Cache rebuild
* Navigate to node/1 // Message 'Node viewed!' displays

My code:

```
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function sitelog_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
    drupal_set_message(t('Test result: @result', array('@result' => 'Node viewed!')));
}

```

Is this the intended behaviour (it doesn't fire *every* time an entity is viewed) of hook\_ENTITY\_TYPE\_view()?

# Answer
> 1 votes
Yes, it is. Entities are render cached. If your output is dynamic/depends on something, you need to provide the necessary cache contexts, use placeholders or something like that.

See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays.

If it's just about debugging locally, there is an example.settings.local.php file that has a example lines to disable those caches, but make sure you always test it with enabled caches before deploying.

---
Tags: 8, hooks
---


# Question
Title: How Do I get specific fields value in Twig?
Background:

I have a `Block view` and content coming from `content_block` with number of fields.

So I want to access those fields value in custom template Is this possible? thanks

# Answer
> 4 votes
In a block twig you can access a field value like this:

```
{{ content['#block_content'].field_myfield.value }}

```

This is the database value of the field.

Most times you want to render a field:

```
{{ content.field_myfield }}

```

This will display the field as it is configured in the view mode.

# Answer
> 0 votes
Yes, it is possible with node template file. In node template file you get all the field values. please check this url for Twig Template naming conventions

# Answer
> 0 votes
This works for me in `block.html.twig` on **Drupal 8.3.4**

`{{ content.field_myfield[0] }}`

The code above will directly display the value of `field_myfield` in the `block.html.twig` template

---
Tags: theming, 8
---


# Question
Title: Using the CodeMirror Syntax Highlighting plugin with CKeditor and the WYSIWYG module
I've installed the latest version of CKeditor and everything works great. However, I wanted to install the CodeMirror Syntax Highlighting Plugin to use it for my editor.

1. I downloaded the plugin: http://ckeditor.com/addon/codemirror
2. I extracted the plugin into the plugins directory
3. I added `config.extraPlugins = '[ codemirror ]';` to the config.js file

When I go to the WYSIWYG Profiles section to enable the plugin, it is not there.

Has anyone successfully done this? I've also cleared the cache multiple times.

# Answer
You can install CodeMirror as a library, and then make a "FULL HTML" profile in WYSIWYG. In practice, you'd get a drop-down entry for it on your edit page (e.g. the ability to switch editors to CodeMirror instead of CKeditor), and a config page within the WYSIWYG module. It's not fully flushed out, but **is workable enough to use in production**, and TwoD has given really strong input for how we could finish it up properly.

Alternately, you could **try to get it working as a CKeditor plugin**. You'd get a button toggle in CKeditor, but no configurability within the WYSIWYG module (which defeats the purpose of using WYSIWYG in the first place, IMHO). Haven't tried that one, but my read is that it works.

If you're not too concerned about configurability, you might be able to just drom WYSIWYG completely, and use the original CKeditor module instead. According to one of the folks in those linked threads, CodeMirror works with it out of the box.

There's also a TinyMCE integration module, wysiwyg\_codemagic, that supposedly works.
> 2 votes

# Answer
The line in the configuration file should be `config.extraPlugins = 'codemirror';`.
> 1 votes

# Answer
I have this working as follows

* I created a custom module
* In the module.php I added a function MYMODULE\_wysiwyg\_editor\_settings\_alter - look it up
* In the alter function, I added `$settings['extraPlugins'] .= ($settings['extraPlugins'])? ",codemirror":"codemirror";`

In the wysiwyg profile editor, it doesn't show up. But when I use the default 'source' button, it uses codemirror now. Which is WAY nicer :-)
> 0 votes

---
Tags: 7, wysiwyg
---


title: How do I lazy load on a view?

text:
# Question
Title: How do I lazy load on a view?
I have a view listing news items.

Is is possible to lazy-load them, so when I scroll to the bottom of the screen, it will load more news items?

# Answer
> 4 votes
There are many modules available for your requirements. You will need to decide which module fits your requirements.

These are some useful modules.

1. Views Infinite Scroll
2. Views Load More
3. Image Lazyloader

# Answer
> 1 votes
There is a module for that: views infinite scroll. https://www.drupal.org/project/views\_infinite\_scroll

---
Tags: 7, views
---


# Question
Title: Do not include certain pages from Search
I have 3 pages I wish to exclude from search. Is there a way to exclude them from coming up in the search results? Incidentally, is it also possible for other content types other than Pages alone?

# Answer
> 7 votes
I haven't tried this in Drupal 7, but it doesn't seem to have changed much. There is an easy "hack" and a "better" way to do this:

The easy way is to override search-result.tpl.php. You can copy the default search-result.tpl.php file from the core search module into your theme. Then, inside the template you can use code like this to exclude results based on node ID:

```
 if ($result["node"]->nid != <excluded nid>) {
      // search result display code
 }

```

The only drawback with this approach is that you will have certain pages of search results that have less results than others (if you show 10 results per page and you don't display 3 on one page, then you will only have 7 results). You could also do similar hiding in template\_preprocess\_search\_result with the same drawback.

The right/"better" way to do this is to actually exclude the list of nodes from ever being indexed. To do that you'll have to implement hook\_query\_alter. You can check out a post describing exactly how to do this over on Phase2's blog.

As you can see in the blog entry, you can also exclude by content type.

Note that the Drupal 6 way was to use hook\_db\_rewrite\_sql. There is a post over at Lullabot on that.

# Answer
> 4 votes
You can use Views to override search results (including all its features: filtering, sorting, etc).
Create a custom field such as "Exclude this node from search," and set the filter to exclude nodes with that field or/and certain content types.

# Answer
> 2 votes
You might also try the module Search exclude nid. It is very easy to use. I did a test and it did exactly this and not anything else.

**Another option:** It appears the Search configuration module (search\_config 7.x-1.1-beta2 or above) also have some ability to restrict search results from showing individual items. The Search configuration module can also restrict search results by the content type. This is a role based restriction.

# Answer
> 0 votes
You can use the Search Configuration module. Once installed, just navigate to node you want to exclude, go to it's edit page, and scroll all the way down to 'Publishing options' -- you'll see an option to exclude the node from search results.

There's also the Search exclude nid module, which is more lightweight... but you'll have to *manually* type in each node you want to exclude.

# Answer
> 0 votes
For Drupal 7. You can hide the node from search results by using custom field. In my case, I have created a custom field in the name of **Archive** to the desired content type and with the help of that custom field you can write the **my\_module\_query\_alter** functionality.

**Code**

```
function my_module_query_alter(QueryAlterableInterface $query) {
 $is_search = $is_node_search = FALSE;
 $node_alias = FALSE;
 foreach ( $query->getTables() as $table ) {
   if ( $table['table'] == 'search_index' || $table['table'] == 'tracker_user') {
     $is_search = TRUE;
   }
   if ( $table['table'] == 'node' || $table['table'] == 'tracker_user') {
     $node_alias = $table['alias'];
     $is_node_search = TRUE;
   }
 }

 if ( $is_search && $is_node_search ) {
   $nids = [];
   // Run entity field query to get nodes that are 'suppressed from public'.
   $efq = new EntityFieldQuery();
   $efq->entityCondition('entity_type', 'node')
     ->fieldCondition('field_archive', 'value', 1, '=');
   $result = $efq->execute();
   if ( isset($result['node']) ) {
     $nids = array_keys($result['node']);
   }
   if ( count($nids) > 0 ) {
     $query->condition(sprintf('%s.nid', $node_alias), $nids, 'NOT IN');
   }
 }
}

```

---
Tags: 7, search
---


# Question
Title: How can I Change Primary Menu block to certain pages using PHP?
I have navigation menu as follow, no 1. is main navigation and no 2. is sub menu of Cooking Menu.

I want Change navigation menu at Cooking Page as follow.  I want to get sub menus of cooking menu into main navigation and remove Cooking. how can I achieve this ? because i'm new to Drupal.

# Answer
> 0 votes
I can think into two alternative ways to do that, maybe it helps:

**With CSS:** Adding those submenu links duplicated in the main level (1) and hiding / showing them depending on the page. Something like:

```
Home        --> Normal
Find store  --> Normal
Cooking     --> (Visible by default, hidden in cooking page)
  |_Recipes --> (Visible by default, hidden in cooking page)
  |_Videos  --> (Visible by default, hidden in cooking page)
  |_Submit  --> (Visible by default, hidden in cooking page)
Recipes     --> (Hidden by default, set to display block in cooking page)
Videos      --> (Hidden by default, set to display block in cooking page)
Submit      --> (Hidden by default, set to display block in cooking page)
Shop        --> Normal

```

---

Another approach could be **with blocks:** You could have 2 menus, the one in your first image:

```
Home
Find store
Cooking
  |_Recipes
  |_Videos
  |_Submit
Shop

```

And another one like the one in your second image:

```
Home
Find store
Recipes
Videos
Submit
Shop

```

And then, through both blocks configuration, you can make the first one visible everywhere **except** in cooking page (e.g. *.../cooking*), and the second one visible **only** in cooking page.

Good luck

---
Tags: theming
---


# Question
Title: Rules loop through list and create nodes with custom title
I'm using rules to create new nodes on 'After saving content of type' event.

To do so I loop through a list of type entity reference

```
Loop
Parameter: List: [node:field-childs]
List item: Current list item (list_item)

```

Inside the loop I Create a new entity,

```
Create a new entity
Parameter: Entity type: Node, Content type: Attendance, Title:
[node:field_childs], Author: [node:author]
Provides variables: CreateAttendancePage (basic_attendance_created)

```

Then I save the entity

```
Save entity
Parameter: Entity: [node], Force saving immediately: true

```

This will title all the new nodes with all the field\_childs values available instead of taking them one by one.

I end up with titles like:

First node: Timmy, Jack, Jimmy, Sam, Hannah

Second node: Timmy, Jack, Jimmy, Sam, Hannah etc.

Instead of:

First node: Timmy

Second node: Jack

# Answer
I've figured it out by myself.

Inside the loop when you create a node the pattern used for the title needs to be from the **Replacement patterns for Current list item** section and in my case, it was the \[list-item:title\] (the title of the current referenced entity in the loop).
> 0 votes

---
Tags: 7, nodes, rules
---


# Question
Title: 8 - Change taxonomy field's link text in view
In drupal 8 when creating a view for taxonomy terms and add a field I enabled

> Link to the Taxonomy term

option. The pathauto module is enabled so it gives following link:

`<a href="/site/taxonomy/taxonomy-term" hreflang="en">Taxonomy Term</a>`

But I want something like this:

`<a href="/site/taxonomy/taxonomy-term" hreflang="en">Read More</a>`

I have created a twig file views-view-field--my-region--name.html.twig as following:

`{{ output -}}`

I cannot go into more deeper with this setup. Can you help me to change the anchor text OR just get the taxonomy term url?

# Answer
> 3 votes
In your view just add the field 'Taxonomy term: Link to Taxonomy term' and change the 'Text to display' to Read more.

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


title: Display user register form in template?

text:
# Question
Title: Display user register form in template?
I'm working on a design heavy site and one of the sections created via the Paragraphs module requires to display the `user_register` form.

I'm currently doing this in the `paragraphs-item--myparagraph.tpl.php` file with the following code:

```
<?php
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
?>

```

This works for showing the form but the problem is that if there are form validation errors, they don't show. I have read that the issue is rendering the form too late but I can't see how I adapt this to Paragraph entities. I have tried using mytheme\_preprocess\_entity to pass the form in but I can't render it?

# Answer
> 1 votes
I ran into something similar recently, and I opted for the Block Reference module.

1. I created a new paragraph called Block Reference
2. Added a block reference field
3. Selected "system blocks" as being referable under the field settings
4. Selected the user login block

and wham bam thank you mam ive got a user login block in a paragraph.

# Answer
> 0 votes
I ended up displaying the form directly on the page instead.

`template.php`

```
function mytheme_preprocess_page(&$variables) {
    if (drupal_is_front_page()){
        if (!user_is_logged_in()) {
            $form = drupal_get_form('user_register_form');
            $variables['register_form'] = drupal_render($form);
        }
    }
}

```

`page--front.tpl.php`

```
<?php print $register_form; ?>

```

---
Tags: theming, forms, paragraphs
---


# Question
Title: How to fix "Hook implementations should not duplicate @param documentation."?
I am using PhpStorm to experiment with cleaning up my code in a custom module. For the following function, I'm getting this warning:

> Hook implementations should not duplicate @param documentation.

```
/**
 * Implements hook_field_widget_form_alter().
 *
 * @param array $element
 * @param array $form_state
 * @param array $context
 */
function mymodule_field_widget_form_alter(&$element, $form_state, $context) {
  if ($context['widget'] instanceof \Drupal\text\Plugin\Field\FieldWidget\TextareaWidget) {
    $element['#after_build'][] = '_mymodule_remove_textarea_help';
  }
}

```

What should I do to fix this? I thought I needed to delete the `@param` comments, but when I do that, PhpStorm complains that I don't have any param comments.

# Answer
The problem is that if you're implementing a hook and you don't need to write more than this:

```
/**
 * Implements hook_field_widget_form_alter().
 */

```

Because you will have all the information in the `hook_field_widget_form_alter()` definition, so just write always in the hooks implementations only this:

```
/**
 * Implements hook_hook_name().
 */

```

In your case:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, $form_state, $context) {
  if ($context['widget'] instanceof \Drupal\text\Plugin\Field\FieldWidget\TextareaWidget) {
    $element['#after_build'][] = '_mymodule_remove_textarea_help';
  }
}

```
> 6 votes

# Answer
Adding an answer for posterity; as per Clive's comment:

You need to turn off the built in PHPStorm inspection that checks for "Missing PHPDoc Comments", then you can safely delete your `@param` blocks.
> 2 votes

# Answer
As others have said, you need to set the PHPStorm config to treat your project as a Drupal project.

Second to that, get up and running with Coder.

Once you have those packages installed, you can wire them up in PHPStorm and set your standards system accordingly or just run the reports from command line. This will make your environment more in-line with the Drupal coding standards instead of the general ones that ship with PHPStorm out of the box config.
> 0 votes

---
Tags: coding-standards
---