# Question
Title: Meta tag module not visible under individual node
I have installed Drupal 8 on my local machine with Metatags module for SEO.

The global settings are available to edit under `Configurations → Search and Metadata → Metatag` but the Metatag tab is not visible when I edit individual articles. I want to change the meta title and description for each article.

# Answer
> 9 votes
When the metatag module is installed, you can create a metatag field in drupal just like creating a textfield, and can be reused in other content types.

# Answer
> 1 votes
You must add a metatag field to the content type. Eg: www.mydomain.com/admin/structure/types/manage/article/fields/add-field More info about metatag module in Drupal 8: https://dev.acquia.com/blog/drupal-8-module-of-the-week/drupal-8-module-of-the-week-metatag/17/02/2016/9716

# Answer
> 0 votes
Do you have a custom html--xXx.html.twig ? Or modified the one of your theme ?

Make sure you render $page\_top, $page and $page\_bottom there.

Also make sure `<head-placeholder token="{{ placeholder_token|raw }}">` is there.

---
Tags: 8, meta-tags
---


# Question
Title: Drupal 7 - Show Child Taxonomies and content in current taxonomy
I have a site that has multiple levels of "Category" taxonomies with varying content within each level.

I have tried for a couple of days but basically i wish to accomplish the following: When a user clicks on a Category view e.g.. /taxonomy/term/% they are presented with a list of child categories and also a list of content items (if any exist) within the parent category.

I have managed to create a view that will show the list of child categories however i cannot combine this with the default term view.

I have attached a mockup of what i wish to accomplish. Any help is greatly appreciated.

Thanks so much for your help.

# Answer
There are a lot of disabled views that come bundled with Views module (check the list of views). One of those disabled views is a replacement for taxonomy/term/%. So, enable it and do all the modifications you need.

You can attach to the header a view with the list of subcategories, and that would fit your needs.
> 0 votes

---
Tags: views, taxonomy-terms
---


# Question
Title: How can I add my Bootstrap classes to a custom menu?
How can I add different Bootstrap menus to menu\_tree\_output()?

I know this is a very common question asked by a number of people earlier. I have found tons of answers, but none of them are working for me. However, I have tried a number snippets and here is the latest piece of code I am working on to get all menus and sub-menus.

```
<?php
  $menuTree = menu_tree_all_data('main-menu');
  $menu_tree_array = menu_tree_output($menuTree);
  print render($menu_tree_array);
?>

```

It works and prints all the submenus, however, It adds the same "menu" class to all parent ul. Rather I would like add sub-menu classes like the below output:

```
<div class="navbar-collapse collapse">
  <div class="menu-top-menu-container">
    <ul id="menu-top-menu" class="nav navbar-nav">
      <li>
        <a href="http://example.com/">Home</a>
      </li>
      <li>
        <a href="http://example.com/biography/">Biography</a>
      </li>
      <li>
        <a href="#">Services</a>
        <ul class="sub-menu"> <!-- Like this. -->
          <li></li>
          <li></li>
        </ul>
      </li>
    </ul>
  </div>
</div>

```

# Answer
What you want is `theme_menu_link()`. See the example here.
> 0 votes

# Answer
You can always use the Menu attributes module.
> 0 votes

---
Tags: theming, navigation
---


# Question
Title: Why does DRUPAL_BOOTSTRAP_PAGE_CACHE phase come before DRUPAL_BOOTSTRAP_DATABASE?
According to this article about `drupal_bootstrap` function, all parameters for drupal\_bootstrap() run sequentially. And if we see the sequence, here first comes - `DRUPAL_BOOTSTRAP_CONFIGURATION`, second `DRUPAL_BOOTSTRAP_PAGE_CACHE` and then database (`DRUPAL_BOOTSTRAP_DATABASE`),

So, My question is cache is itself stored in database, so in order to serve pages from cache, a database connection is a must. Then How Drupal manages these calls sequentially?

Accordingly, `DRUPAL_BOOTSTRAP_DATABASE` should come before `DRUPAL_BOOTSTRAP_PAGE_CACHE`. If not, what is the reason?

# Answer
> 4 votes
Inside of \_drupal\_bootstrap\_page\_cache() the key bit of information is this bit of code

```
  if (variable_get('page_cache_without_database')) {
    $cache_enabled = TRUE;
  }
  else {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
    $cache_enabled = variable_get('cache');
  }

```

The call to bootstrap DRUPAL\_BOOTSTRAP\_VARIABLES will also bootstrap DRUPAL\_BOOTSTRAP\_DATABASE because it's before variables inside of drupal\_bootstrap()

What this means is if your cache doesn't require a database connection (like memcache or filecache) then you can speedup page cache hits by not connecting to the database. The linked article talks about this.

---
Tags: caching, bootstrapping
---


# Question
Title: I can't access private files in CKEditor
I have this site someone else has worked on and they've asked me to see if I could fix something. This site has private files available to users after they've filled in a form (they then get a email with a link to the private file). This all works the way it should.

Now what they want is to be able to add a link or image that is private. When doing this the image doesn't show or the link to the file gives a 403 error.

What is the best way to fix this or make this work.

Search for picture through ckeditor

picture doesn't show

# Answer
If I'm understanding the situation correctly, then the issue is that, by virtue of bring a private file, they would need the right permissions in order to view the file in their browser.

On the sites I work on, we use elFinder, and the permission to allow access is called **Access private files**.

If you're not using elFinder, then there is probably a similar permission that you'll need to enable.

Hope that helps!
> 0 votes

---
Tags: 7, files
---


# Question
Title: What is causing duplicate google analytics?
I am currently using google analytics module in drupal however when i check With Tag assist extension is shows that i am making two calls to google analytics using the same analytics key. I check my inspector and look for analytics.js and it does appear twice.

once in:

```
<!--//--><![CDATA[//><!--
(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","http://dev-website.pantheonsite.io/sites/default/files/googleanalytics/analytics.js?oebw5p","ga");ga("create", "UA-213XXXX-X", {"cookieDomain":"auto"});ga("require", "linkid", "linkid.js");ga("send", "pageview");
//--><!]]>

```

I have no idea where that is being called from and then again in:

```
(Drupal.settings, {"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"test-site","theme_token":"XXXXXXXXXXXXXXXX-y-oO0","js":{"sites\/all\/libraries\/modernizr\/modernizr.js":1,"sites\/all\/libraries\/underscore\/underscore-min.js":1,"sites\/all\/themes\/test-site\/webfonts\/ss-social.js":1,"sites\/all\/themes\/test-site\/webfonts\/ss-symbolicons.js":1,"sites\/all\/themes\/test-site\/webfonts\/ss-standard.js":1,"sites\/all\/themes\/test-site\/js\/jquery\/plugins.js":1,"sites\/all\/themes\/test-site\/js\/jquery\/app.js":1,"sites\/all\/themes\/test-site\/js\/jquery\/test-site-drupal-custom.js":1,"sites\/all\/themes\/test-site\/js\/picturefill.min.js":1,"0":1,"\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.11.2\/jquery.min.js":1,"1":1,"misc\/jquery.once.js":1,"misc\/drupal.js":1,"sites\/all\/modules\/contrib\/jquery_update\/replace\/ui\/external\/jquery.cookie.js":1,"sites\/all\/libraries\/colorbox\/jquery.colorbox-min.js":1,"sites\/all\/modules\/contrib\/colorbox\/js\/colorbox.js":1,"sites\/all\/modules\/contrib\/colorbox\/styles\/default\/colorbox_style.js":1,"sites\/all\/modules\/contrib\/themekey\/themekey_redirect\/themekey_redirect.js":1,"sites\/all\/modules\/contrib\/google_analytics\/googleanalytics.js":1,"2":1,"misc\/autocomplete.js":1,"sites\/all\/modules\/contrib\/search_api_autocomplete\/search_api_autocomplete.js":1,"3":1,"http:\/\/w.sharethis.com\/button\/buttons.js":1,"4":1,"sites\/all\/modules\/contrib\/field_group\/field_group.js":1,"\/sites\/all\/libraries\/jquery\/jquery-ui.min.js":1,"\/\/maxcdn.bootstrapcdn.com\/bootstrap\/3.3.4\/js\/bootstrap.min.js":1,"\/\/use.typekit.net\/hhy3ulu.js":1,"sites\/all\/themes\/basic\/js\/build\/scripts.js":1,"sites\/all\/themes\/basic\/js\/build\/modernizr.js":1},"css":{"modules\/system\/system.base.css":1,"modules\/system\/system.menus.css":1,"modules\/system\/system.messages.css":1,"modules\/system\/system.theme.css":1,"sites\/all\/modules\/contrib\/calendar\/css\/calendar_multiday.css":1,"modules\/comment\/comment.css":1,"sites\/all\/modules\/contrib\/date\/date_api\/date.css":1,"sites\/all\/modules\/contrib\/date\/date_popup\/themes\/datepicker.1.7.css":1,"sites\/all\/modules\/contrib\/date\/date_repeat_field\/date_repeat_field.css":1,"modules\/field\/theme\/field.css":1,"modules\/node\/node.css":1,"sites\/all\/modules\/contrib\/payment_forms\/payment_forms.css":1,"modules\/search\/search.css":1,"modules\/user\/user.css":1,"sites\/all\/modules\/contrib\/webform_paymethod_select\/webform_paymethod_select.css":1,"sites\/all\/modules\/contrib\/workflow\/workflow_admin_ui\/workflow_admin_ui.css":1,"sites\/all\/modules\/contrib\/views\/css\/views.css":1,"sites\/all\/modules\/contrib\/ckeditor\/css\/ckeditor.css":1,"sites\/all\/themes\/basic\/css\/tabs.css":1,"sites\/all\/modules\/contrib\/colorbox\/styles\/default\/colorbox_style.css":1,"sites\/all\/modules\/contrib\/ctools\/css\/ctools.css":1,"sites\/all\/modules\/contrib\/facebook_pull\/facebook_pull.css":1,"sites\/all\/modules\/contrib\/panels\/css\/panels.css":1,"sites\/all\/modules\/contrib\/search_api_autocomplete\/search_api_autocomplete.css":1,"sites\/all\/modules\/contrib\/field_group\/field_group.css":1,"sites\/all\/themes\/test-site\/webfonts\/ss-social-regular.css":1,"sites\/all\/themes\/test-site\/webfonts\/ss-symbolicons-block.css":1,"sites\/all\/themes\/test-site\/webfonts\/ss-standard.css":1,"\/\/ajax.googleapis.com\/ajax\/libs\/jqueryui\/1.10.4\/themes\/ui-lightness\/jquery-ui.css":1,"sites\/all\/themes\/test-site\/css\/test-site-app.css":1,"sites\/all\/themes\/test-site\/css\/test-site-drupal-custom.css":1}},"colorbox":{"opacity":"0.85","current":"{current} of {total}","previous":"\u00ab Prev","next":"Next \u00bb","close":"Close","maxWidth":"98%","maxHeight":"98%","fixed":true,"mobiledetect":true,"mobiledevicewidth":"480px"},"ThemeKeyRedirect":{"checkOnce":false,"redirectOnce":false},"googleanalytics":{"trackOutbound":1,"trackMailto":1,"trackDownload":1,"trackDownloadExtensions":"7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip"},"urlIsAjaxTrusted":{"\/":true},"field_group":{"div":"full"}});

```

Which most likely being called from the googleanalytics module. I tried removing the source script and directory for the first call but both the script and file were created again.

can anyone help me identify what is creating the first call to analytics.js?

# Answer
The first instance was being created by Google Tag Manager module. Since this module uses a different type of key than the Google Analytics module I didnt think it was adding the additional analytics.js
> 1 votes

---
Tags: 7, javascript, google-analytics
---


# Question
Title: Need an email sent automatically when a customer abandon cart
I am using Drupal 7 with drupal commerce. I require an email sent automatically to those customers who abandon their cart.

Is there any way?

# Answer
> 1 votes
You could use the commerce notification module:

> This module allows you to notify your customers by email about their abandoned their cart.

This module is 100% integrated with the Commerce Views Bulk Operations (VBO) module

**How does that work ?**

Go to the view page : /admin/commerce/orders/abandoned\_carts Select the customers you want to notify (the module does not allow you to notify a user more than once... Don't be a spammer ^^) Select the component : "Notify the user of his abandoned cart" and click on "Execute"

Although it has not a estable release you can download it from git with a git clone:

```
git clone --branch 7.x-1.x http://git.drupal.org/project/commerce_notification.git
cd commerce_notification

```

# Answer
> 0 votes
The admin/commerce/orders/abandoned\_carts view had not being added to the code it self in 7.x-1.x branch, you should clone the branch new-table instead.

See this issue

Despite of the view not having a url, you can create a new view with the same filter criteria/fields.

But when i active the bulk operation "Notify the user of his abandoned cart" created by this module i get an ajax error, but that should be asked in another question.

# Answer
> 0 votes
I also had the same issues as the previous posters and was frustrated by the lack of solutions or modules out there so I rolled my own.

My solution uses Views, Views Rules, Commerce ProdNodeLink, Rules, PHP Filter, and Mimemail and runs on hourly cron.

## Create a Views block

The views block will output a list of order numbers, first names and email addresses that will be used by Rules.

* *Format:* Unformatted list
* *Advanced:* Add relationship to "Commerce Order: Referenced customer profile" and be sure to select the profile related to billing information (commerce\_customer\_billing)
* *Fields:*
    + Order Number
    + First Name from the related billing profile
    + Email Address from the billing profile
* *Filter Criteria:*
    + "Commerce Order: Order state" is one of "Shopping cart" or "checkout"
    + "Commerce Order: Order status" is one of "Shopping cart (Shopping cart)", "Checkout: Checkout (Checkout)", "Checkout: Billing Information (Checkout)", "Checkout: Shipping (Checkout)", "Checkout: Review (Checkout)". Your mileage may vary on this one. Essentially you want to choose any status including cart through the last page of checkout in your setup, not including the order confirmation page. ;)
    + "Commerce Customer profile: Email address (field\_email\_address)" should be set to "Is not empty (NOT NULL)". We want to make sure that there is a value for the email address.
    + "Commerce Order: Order total (commerce\_order\_total:amount)" should be set to greater than 0. This is a second control since a user could go through checkout but then remove all products from the cart. We don't want to email those people.
    + "Commerce Order: Updated date" should be set to "In between". The "value type" should be set to "An offset from the current time such as "+1 day" or "-2 hours -30 minutes"" where the Min value is "-2 hours" and the Max value is "-1 hours". We only want to fetch abandoned orders that are between 1 and 2 hours old. This way we avoid our system from emailing people too quickly (e.g., a user going through checkout at 1:59 won't be emailed by the cron trigger at 2:00).

Your view may or may not be empty if you don't have any abandoned carts in the specified window.

## Set up the Views Rules display

While in your view from step 1, click "Add" and select "Rules". This will create a rules block for your view that you can use within Rules to iterate over.

Click "edit field info" next to "Row variables" and enable each of the 3 fields you added in step 1. I checked "Use rendered result" for each. The data type should be "Text" for each field.

Save your view.

## Set up the Rule

* *Event:* "Cron maintenance tasks are performed"
* *Conditions:* "Execute custom PHP code"
    + Value: `return views_get_view_result('YOUR_VIEWS_BLOCK_MACHINE_NAME', 'display_title');`
* *Actions:*
    1. Click "Add view loop" and choose the view you just created. Doing this will expose the view to rules and allow you to loop through the items in the view.
    2. Click "Send HTML e-mail"
        + Give your email a machine name
        + Use the email address token (mine was \[field-email-address:value\]) as the "To:" value. Check your Replacement Patterns or PHP Evaluation variables for clues here.
        + Enter other details if needed (bcc, cc, etc.)
        + The Body has PHP in it and is styled to have a header and a footer. In the body the list of products that were left inside the cart are output in a table with an image on the left and product title on the right, each of which links to the product node alias on your website. Mine is like so (be sure to change your variables the ones supplied by your PHP Evaluation):

\[The only way I could get the code block to show is to include this line (ugh):\]

```
<table style='font-family: arial; font-size: 15px;'><tbody>
<?php
$product_ids = array();
foreach (entity_metadata_wrapper('commerce_order', $order_number)->commerce_line_items as $delta => $line_item_wrapper) {
  if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
    $product_ids[] = $line_item_wrapper->commerce_product->raw();
  }
}

foreach ($product_ids as $p) {
  // Get the product details by the Commerce function
  $product = commerce_product_load($p);

  // Get the product by Entity in order to eventually retrieve the node ID from Commerce ProdLink module
  $product_wrapper = entity_metadata_wrapper('commerce_product', $p);
  $display_node_ids = $product_wrapper->display_node_ids->value();

  foreach ($display_node_ids as $nid) {
    print '<tr><td style="font-family: arial; font-size: 15px;"><a href="' . url('node/' . $nid, $options) . '"><img src="' . $product->field_image_square["und"][0]["uri"] . '" height="125" width="125" /></a></td><td style="font-family: arial; font-size: 15px;"><a href="' . url('node/' . $nid, $options) . '">' . $product->title . '</a></td></tr>';
  }
}
// Write to the log
watchdog('abandoned cart email', 'Abandoned Cart Notification Email Sent to !email (cart !cart)', array( '!email' => $field_email_address, '!cart' => $order_number ), WATCHDOG_INFO);
?>
</tbody></table>

```

And for anyone who is wondering what $options is, it's just a variable declared earlier for adding UTM codes to the link:

```
<?php
// Setup URL arguments for tracking
$options = array('absolute' => TRUE, 'base_url' => 'https://example.com', 'https' => TRUE, 'query' => array('utm_source' => 'email', 'utm_medium' => 'email', 'utm_campaign' => 'abandoned cart email', 'utm_content' => 'product link'));
?>

```
3. Indent the "Send HTML e-mail" element

You should now have an automated abandoned cart email checker running hourly!

---
Tags: 7, commerce
---


# Question
Title: Migrate file field paths not the actual file
Say I drag and drop files from a source site into the folder structure of a new site (destination site) that I'm migrating content to. The source sites file paths are the exact same as the destinations paths.

Source: `sites/default/files/attachments`

Destination: `sites/default/files/attachments`

So instead of migrating the actual file I just need Drupal to point to the same location as the source site and the file will be there but when migrating the files over it wants to migrate the entire file.

Is this possible? Maybe after content migration I will need to reconfigure the attachments paths?

# Answer
> Say I drag and drop files from a source site into the folder structure of a new site (destination site) that I'm migrating content to.

Dont do this. Migrate D2D has file handling classes to move the files for you. In the UI it's super easy, in code you select the correct file handing class.

Read the documentation on migrating files for D2D. There are 4 cases it supports, depending on how the remote file needs to be fetched.

In the D2D UI you just want to be sure to setup the File\_class value for your migration ok. Typically the Files are migrated (moved) to Drupal as 1 of the 1st auto-generated migrations. Then in Node content that relates the migrated files to the (migrated) Node you set file class to `FileFID` and select the previous Source Migration that moved the file into the new site.

## EDIT

So for example with a website with existing image fields in a content type. On the destination Drupal 7 side of the migration I tell it the legacy field and tell the configuration to use `MigrateFileFID` this will map just the file ID between the 2 drupal instances:

See `field_ofellow_photo` above for an example of this configuration for D6 -\> D7.

Then Migrate will see the information for the migration steps:

If you use `MigrateFileFID` then Migrate doesnt (necessarily) move the files I believe if you leave off the destination information, it just moves FIDs. See the documentation on MigrateDesinationFile and MigrateFileFid.
> 1 votes

# Answer
You can set up the field mapping to reuse existing files:

```
$this->addFieldMapping('destination_file_field','source_file_field');
$this->addFieldMapping('destination_file_field:file_replace')->defaultValue(MigrateFile::FILE_EXISTS_REUSE);

```
> 0 votes

---
Tags: migrations
---


# Question
Title: How do I print the name of the field for a submission a value?
I have a custom webform confirmation page where I am print the submission values using the following:

```
<?php print $submission->data[67][0]; ?>

```

How can I print the title of the form field for the above data?

# Answer
> 2 votes
The Webform submission object's data parameter is a keyed array of component ID's/component submission data. The object doesn't contain the component field name so you'll need to reference its value through data attached on the node.

For example:

```
$webform_node = node_load($submission->nid);
foreach ($submission->data as $cid => $data) {
  print $webform_node->webform['components'][$cid]['name'] . ':' . $submission->data[$cid][0];
}

```

---
Tags: webforms
---


title: how do I sum a table column?

text:
# Question
Title: how do I sum a table column?
Is there a way to sum a numeric value and display it from a field column data in a table view format using search api? I have a DB server (not solr). I need facets.

I've tried the following methods:

1.- search api node index views has no "aggregation settings" (not possible here).

2.- Views calc module (goes out of memory).

3.- Views Aggregator Plus module, "it works", but always result is equal to zero.

I'm run out of posible sulutions, please help.

# Answer
This module does the job, https://www.drupal.org/project/views\_summarize, also I'm using a bootstrap sub-theme and all modules above mensioned break css, and this module does not.
> 0 votes

---
Tags: 7, search
---


# Question
Title: Remember webform textfield for next entry
I would like to know what is module to remember webform textfield or select option, so once fill in or selected, the next entry use the previous entry. In webfform autocomplete, typing several characters still required.

Is that possible to do that?

# Answer
This is the use case of the Webform Field Repeat module:

> The Webform Field Repeat module enables the webform to remember selected field entries from current submission for up to an hour. It uses the $\_SESSION to do so. If the session is active, the form will be populated with selected entries from remembered submission when opened again.
>
> The fields can be selected on Webform \>\> Form settings for each individual webform. Once the fields has been selected the end users will see a check box at the bottom of the form that they can check to have the form populated when they open the form for a new submission. This module depends on Webform module.
> 1 votes

---
Tags: webforms
---


# Question
Title: Why does module_invoke() return an empty array for anonymous users?
I'm using module\_invoke to return an array of blocks in a hook\_block\_list\_alter

```
function MY_MODULE_block_list_alter(&$blocks) {

 $foo = &drupal_static('foo');
 foreach ($blocks as $key => $block) {
  if ($block->module == 'bean') {
   $bar = module_invoke($block->module, 'block_view ', $block->delta);
   $foo[] = $bar;
  }
 }
 return $foo;
}

```

When I'm logged in with admin privileges, $bar will be an array containing $bar\['content'\], $bar\['subject'\] etc. But for anonymous users, the array is empty. I can't find any reason for this, hopefully I'm missing something obvious and easy (to others!).

# Answer
> 0 votes
You are invoking the function bean\_block\_view(), which contains this code:

```
if (bean_access('view', $bean) && $bean) {
  $content = $bean->view($bean->view_mode);
  if (!is_array($content)) {
    $content = array(
      '#markup' => $content,
    );
  }

  $return = array(
    'content' => $content,
    'subject' => isset($bean->title) ? $bean->title : '',
  );
}

```

Looking at the first line of code, you can see the block is only built if the viewer has 'view' access for beans.

So it's a permissions issue of some sort with the beans module. Anonymous users don't have the required permission, so the block is empty.

---
Tags: blocks, hooks
---


# Question
Title: How to recalculate the current User Points?
I manually deleted a couple of User Point transactions in my database's table **userpoints\_txn**. This results in inaccurate current User Points in the table **userpoints\_total**. Clearing caches or running cron doesn't resolve this problem.

Is there a way to recalculate the current total User Points for all users?

# Answer
You should have used the Userpoints admin UI or its API (e.g. `userpoints_userpointsapi()`) to make changes in the records. That way you can make point adjustments without the problem of database integrity that you've introduced. If possible, I'd restore the DB rows and adjust the point records with the UI/APi.

In absence of that being a possibility, you can see that `_userpoints_update_cache()`, the function used for maintaining updated `userpoints`/`userpoints_total` tables, requires those tables to always be consistent, as they are referenced when transactions are added/updated/removed. Thus, the userpoints code won't be much help here.

You'll have to do an aggregate SQL query on the `userpoints_txn` table for each impacted user to determine their updated score and use that to update the `userpoints`/`userpoints_total` tables accordingly.
> 1 votes

---
Tags: 7, userpoints
---


# Question
Title: How do I programmatically generate an entity form?
I need to programmatically generate the entity form for my custom entity - basically get the same output that happens when you call

```
\Drupal::formBuilder()->getForm('form namespace')

```

When I try to do that with my entity form **I get the error**:

```
Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId() (line 77 of core/lib/Drupal/Core/Entity/EntityForm.php).

```

Really stumped on how to proceed.

---

Here's an obfuscated version of code I'm using

Entity Definition:

```
/**
 * Defines the My Entity entity.
 *
 * @ingroup my_module
 *
 * @ContentEntityType(
 *   id = "my_entity",
 *   label = @Translation("My Entity"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\my_module\MyEntityListBuilder",
 *     "views_data" = "Drupal\my_module\Entity\MyEntityViewsData",
 *     "translation" = "Drupal\my_module\MyEntityTranslationHandler",
 *
 *     "form" = {
 *       "default" = "Drupal\my_module\Form\MyEntityForm",
 *       "add" = "Drupal\my_module\Form\MyEntityForm",
 *       "edit" = "Drupal\my_module\Form\MyEntityForm",
 *       "delete" = "Drupal\my_module\Form\MyEntityDeleteForm",
 *     },
 *     "access" = "Drupal\my_module\MyEntityAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\my_module\MyEntityHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "my_entity",
 *   data_table = "my_entity_field_data",
 *   translatable = TRUE,
 *   admin_permission = "administer as my_entity entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/my_entity/{my_entity}",
 *     "add-form" = "/admin/structure/my_entity/add",
 *     "edit-form" = "/admin/structure/my_entity/{my_entity}/edit",
 *     "delete-form" = "/admin/structure/my_entity/{my_entity}/delete",
 *     "collection" = "/admin/structure/my_entity",
 *   },
 *   field_ui_base_route = "my_entity.settings",
 *   constraints = {
 *     "CustomContraint" = {}
 *   }
 * )
 */
class MyEntity extends ContentEntityBase implements MyEntityInterface {

```

Form namespace

```
namespace Drupal\my_module\Form;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for My Entity edit forms.
 *
 * @ingroup my_module
 */
class MyEntityForm extends ContentEntityForm {

```

---

Okay, so this is what I've found so far. User **oknate**'s answer partially works; I also had to add a dummy function to my container form class to get around a callback error, which looked like this:

```
 public function processForm($element, FormStateInterface $form_state, $form)
  {
    return $element;
  }

```

This is probably not the right way to do this, but it does result in a form object that will render in another form.

# Answer
> 21 votes
You can use the entity form builder service. I was able to load the user form this way (with $entity being the current user):

```
$entity = User::load($uid);
$user_form = \Drupal::service('entity.form_builder')->getForm($entity, 'default');

```

If you want to get the user register form (which is basically an entity form without a saved entity), you can just use the create method on your entity class before passing it to the form:

```
$entity = User::create();
$user_form = \Drupal::service('entity.form_builder')->getForm($entity, 'default');

```

# Answer
> 5 votes
Entity forms don't work without an entity. If you want an empty form then use a newly created entity instance. You can use this example from the node entity:

```
/**
 * Provides the node submission form.
 *
 * @param \Drupal\node\NodeTypeInterface $node_type
 *   The node type entity for the node.
 *
 * @return array
 *   A node submission form.
 */
public function add(NodeTypeInterface $node_type) {
  $node = $this->entityManager()->getStorage('node')->create(array(
    'type' => $node_type->id(),
  ));

  $form = $this->entityFormBuilder()->getForm($node);

  return $form;
}

```

The entity form builder is injected in the controller base class. So usually you use a controller to build entity forms.

When creating a node you need to define a bundle (content type), for which the entity form will be built. If your entity has no bundles you can use an empty array.

---

**Comments**

Comments need more work, because they are attached to an entity field.

Example how to build a form for the comment field of a node:

```
$comment = $this->entityTypeManager()->getStorage('comment')->create([
  'entity_type' => 'node',
  'entity_id' => $node->id(),
  'field_name' => 'comment',
]);
$build = $this->entityFormBuilder()->getForm($comment);

```

Or the same outside of a controller without injected services:

```
$comment = \Drupal::entityTypeManager()->getStorage('comment')->create([
  'entity_type' => 'node',
  'entity_id' => $node->id(),
  'field_name' => 'comment',
]);
$build = \Drupal::service('entity.form_builder')->getForm($comment);

```

# Answer
> 3 votes
Just to clarify, the below code does work for me in Drupal 8.2.x:

```
$form = \Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class);

```

---
Tags: forms, 8
---


title: Create chart for fivestar note

text:
# Question
Title: Create chart for fivestar note
I'm using Drupal 7, and Fivestar.

I try to display notes in the format of a pie chart.

If the note (= rating) is 5,2 on 10, I would like to have a circle of this type :

I tried Charts (with Google Charts as its charting engine) and Google chart Tools, but I do not manage to obtain what I wish (using the Views integration).

With Google chart tools, I have this problem (only one value is shown), and with Chart nothing displays (i do not use aggregation, just fivestar field in views).

Would you know a solution?

A tabular of the data which I wish to display :

# Answer
> 1 votes
# Solution 1 - Use Charts to create a pie chart

The sample image in your question doesn't look like a pie chart to me, instead it rather looks like a ***Gauge*** chart. If you want to try to create a pie chart anyway, using the Charts module, then have a look at this feature request (which allows you to pass "library specific options"). Comment #9 in it contains a patch that you'll need for it (using Google Charts as the rendering engine).

After you applied that patch, you'll be able to pass any of the specific options to the Google Charts charting engine that correspond to the chart you're trying to create.

If applying the patch is not sufficient, then I'd recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

> You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.

# Solution 2 - Use Charts to create a Gauge chart

Your sample image in your question rather looks like a ***Gauge*** chart. Have a look at the Charts issue about Support for gauge charts. After you apply the patch included in comment # 4 of this issue, you'll be able to use the Charts API to create such Gauge charts (using Google Charts as your charting engine). BTW, you can also use this specific SimplyTest.Me link (which has this patch enabled).

Here is a sample of 2 such charts I created in my own environment (using that patch):

---

---

The first (left) chart is to show a rating like 5.7, and the second (right) chart is to show a rating like 7.2 (both ratings on a scale of 10). Attention: I haven't found any specific option (yet) to show that value of 5.7 (and 7.2) in the Gauge chart, instead of the rounded value 6 (and 7) near the bottom. Though the (red) pointer within the chart seems to correctly reflect the actual values already.

My PHP code for rendering the above 2 Gauge charts looks like so (the various options I used should be self explaining):

```
<?php

 $chart = array(
    '#type' => 'chart',
    '#chart_type' => 'gauge',
    '#chart_library' => 'google',
    '#title' => t('Gauge Chart'),
    '#min' => 0,
    '#max' => 10,
    '#width' => 300,
    '#height' => 300,
    '#greencolor' => '#00AA10',
    '#greenfrom' => 0,
    '#greento' => 5,
    '#redfrom' => 8,
    '#redto' => 10,
    '#redcolor' => '#FF3333',
    '#yellowfrom' => 5,
    '#yellowto' => 8,
    '#yellowcolor' => '#66BB88',
    '#minorticks' => 5,
  );

echo "<p>Left Gauge chart (= Rating 1) : 5.7 / 10 ; Right Gauge chart (Rating 2) : 7.4 / 10 </p>";

  $chart['rating1'] = array(
    '#type' => 'chart_data',
    '#title' => t('Rating 1'),
    '#data' => array(array('Rating1', 5.7)),
  );

  $chart['rating2'] = array(
    '#type' => 'chart_data',
    '#title' => t('Rating 2'),
    '#data' => array(array('Rating2', 7.2)),
  );

  $example['chart'] = $chart;

  return drupal_render($example);
?>

```

If you paste the above code in the body of any content type that allows using the PHP filter, and assuming you have a working internet connection (prereq to use Google Charts), you should get a similar chart in your own environment (provided you also enabled the patch mentioned before).

With the above solution that uses the Charts API, it should be possible to use the same technique for adding an extra column in your tabular Views display, using "rewrite results", in which you also refer to the actual value of the ***Score*** column for each of your views result rows (so that you get 1 Gauge chart somewhere to the right of your Score column).

Disclosure: I'm a **co**-maintainer of the Charts module.

---
Tags: 7, entities, rating, charts
---


# Question
Title: Hide Authoring info on certain pages/nodes
I am looking for a way to hide the "Submitted By: .... on ...." info on certain pages. I am aware that it can be removed from all pages of the 'Basic Page' or 'Article' type through the configuration settings, however I would like the info to appear on all pages unless I turn on a setting whilst creating/editing the page which hides it on that certain page. Does anyone know of a way to do this? Thanks,

# Answer
You could add a checkbox field to the content type, and adjust the node.tpl file. If the box is not checked, don't print submitted by.

Add the field to all content types (sounds like thats what you asked for) and remove it from each display under "Manage Display".

Then, in template.php, implement `template_preprocess_node`:

```
mythemename_preprocess_node(&$variables) {
  $node = $variables['node'];

  // here we are creating a brand new variable
  // true, unless otherwise set by editors
  $variables['show_authoring'] = TRUE;

  // the field exists on the node object
  // update our custom variable to this field value
  if (isset($node->field_show_authoring)) {
    $variables['show_authoring'] = $node->field_show_authoring[LANGUAGE_NONE][0]['value'];
  }
}

```

If you want all nodes have this, you can copy in node.tpl.php to your theme or edit the one in your theme if it exists, and do:

```
<?php if ($display_submitted && $show_authoring): ?>
  <div class="submitted">
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

```

You could remove `$display_submitted` if you wanted to, I left that there in case you wanted control in the future to completely disable showing authoring for certain content types, like Webform for example. My syntax should be correct but I did not have a chance to test this in a sandbox.

See more:
> 1 votes

---
Tags: 7, theming, nodes
---


# Question
Title: How to migrate joomla users mysql file to drupal users. I have only MySQL database backup. I don't have files
I have only MySQL database backup. I don't have files.

# Answer
> 1 votes
Install your backup into a MySQl database, and use the Migrate module (http://dgo.to/migrate) to migrate your users into Drupal.

---
Tags: migrations, backups
---


# Question
Title: #markup is replacing colon in <gcse:search... tag with space
I have the following code:

```
 return array(
      '#type' => 'markup',
      '#markup' => '<gcse:search queryParameterName="query" resultsUrl="'
        . Url::fromRoute('cn.search', [], ['absolute' => TRUE])->toString()
        . '"></gcse:search>',
      '#allowed_tags' => ['gcse', 'gcse:search'],
    );

```

but the output is:

```
  <gcse search queryparametername="query" resultsurl="http://d8.constitutionnet.org/search2"></gcse>

```

How do I prevent the colon being converted to a space?

# Answer
Use an inline template:

```
  return [
    '#type' => 'inline_template',
    '#template' => '<gcse:search queryParameterName="query" resultsUrl="{{ url }}"></gcse:search>',
    '#context' => [
      'url' => Url::fromRoute('cn.search', [], ['absolute' => TRUE]),
    ],
  ];

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Is it possible to backup created block as a module?
My question seems pretty simple but is very important: IS it possible or any solution to backup created block as a module to avoid duplication work, because there are times need to do something similar for multiple times and sites.
Like:

* Create simple block with social media links, icon and some stable text.
* Create a view that show five recent content title of custom content type as customized block for several sites.
and all repetitive and permanent tasks can be done each time.

Thanks for any help and feedback.

# Answer
> 1 votes
Exporting and importing blocks in Drupal 8 are quite easy (thanks to new configuration system). You don't need to create a module for this. In Drupal 8 configuration is stored in yml files. You can export and import it on the following page:

*Administration \>\> Configuration \>\> Development \>\> Synchronize \>\> (import / export) \>\> Single item*

It works for all kind of blocks except "Custom blocks" because they are actually not a configuration but content like nodes, comments etc. As a workaround you can use Simple block module mentioned above.

Note, that in some cases you also need to export block configuration dependency in a separate yml file. For instance for a block that shows five recent content titles you need to export underlying view and all its dependencies. You may also checkout Features module for some advanced configuration package tools.

---
Tags: 8, blocks, backups
---


# Question
Title: Alter values available in node reference field based on term reference
I have a content type structure as mentioned below,

* Content Type
    + Field Collection
        - Term Reference
        - Node Reference
        - Text Field

What I want to accomplish is, As I select the Term Reference value; the available values in node reference field with auto complete widget should only be of those nodes that have the term reference value assigned.

FYI The field collection will have multiple values.

# Answer
It looks like I am late to answer your question :), but I hope this will help someone.

Using Dynamic dependent fields you can achive this, but it support `Entity Reference`field not `Node Reference` Documentation for Dynamic dependent fields
> 0 votes

---
Tags: nodes, taxonomy-terms
---


# Question
Title: Unable to upload file from $_FILES array in drupal7
I am trying to upload file from `$_FILES` array. but getting following error in drupal7.

```
The specified file temporary://fileOYnPHK could not be copied, because the destination directory is not properly configured.
This may be caused by a problem with file or directory permissions. More information is available in the system log.

```

The `sites/default/files` has permissions `777`

Here is my code

```
if($_FILES['files']['name']['field_tenant_review_ref_und_form_field_tenancy_document_und_0']){
    $file_path = file_save_data(file_get_contents($_FILES['files']['tmp_name']['field_tenant_review_ref_und_form_field_tenancy_document_und_0']),
    'public://sites/default/files/'.$_FILES['files']['name']['field_tenant_review_ref_und_form_field_tenancy_document_und_0']);
   }
   //$tenant_review->field_tenancy_document->file->set($file_path);

```

Is there any mistake in code? Please suggest.

# Answer
The problem is not with your **Public file system path** but with your **Temporary directory**; normally it is `/tmp` if you're in a Mac or Linux server.

You can check that the Temporary Directory is well configured, maybe it is pointing to a non-existing path.

To check the configuration in Drupal 7 you must go to *Configuration* \> *Media* \> *File system*.
> 0 votes

---
Tags: files
---


# Question
Title: Drupal 8 : Render a field collection item in a Twig template
In Drupal 8, I have a content type which use Field Collection Module like that :

* `field_body` (FieldCollection, repeatable)
    + `field_image_alignment`(Boolean)
    + `field_picture` (Image)
    + `field_free_text` (Long Text)

I want to theme this fields. I overrided the field template with a file named `field--node--field-body--news.html` (news is the content type that contains theses fields.).

Default template is this :

```
{% for item in items %}
    <div{{ item.attributes }}>{{ item.content }}</div>
{% endfor %}

```

And my template overrided is like that :

```
{% for item in items %}
  {% if item.content['#field_collection_item'].field_image_alignment.value == 1 %}
    {{ dump(item.content['#field_collection_item'].field_picture) }}
    {% endif %}
{% endfor %}

```

How can I render "child" fields `field_pictures`, `field_free_text` ? I used `item.content['#field_collection_item'].field_image_alignment.value`to access to the plain value but I would like to have the rendered view.

Thanks a lot.

# Answer
I've just started learning Drupal and encountered the same issue. I solved it by creating custom field formatter:

```
public function viewElements(FieldItemListInterface $items, $langcode)
{
  $elements = array();
  foreach ($items as $delta => $item)
    if ($item->value !== NULL)
    {
      $builder    = \Drupal::entityTypeManager()->getViewBuilder('field_collection_item');
      $elements[] = $builder->build($builder->view($item->getFieldCollectionItem()));
    }
  return $elements;
}

```
> 2 votes

# Answer
Use this module for Nice Table format Look Link: https://www.drupal.org/project/reference\_table\_formatter
> -1 votes

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


# Question
Title: Temporary add role by token for a particular page to anonymous user
I have a specific task: I need to give a temporary access to particular unpublished nodes for anonymous users using access token. Anonymous is a key feature, so I can't create a limited user account by some reasons.

I found a rough temporary solution by adding a field "access token" to my node type, creating a role with access to unpublished nodes (using view unpublished module) and by changing user\_access function. I added the following strings:

```
 if ($_GET['access_token'] && arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {

        $node = node_load(arg(1));

        if (isset($node->field_access_token['und'][0]['value']) && $node->field_access_token['und'][0]['value'] == $_GET['access_token']) {

            $account->roles[6] = 'unpublishedaccess';
        }
    }

```

How can I do similar but without changing Drupal core files?

# Answer
Assuming that this question is about D7, you could use the Rules module for this, combined with enforcing the usage of an URL argument which must include the correct token.

Here is an example of a relative path you could use/enforce: `/node/123?SomeUrlArg=456`, which would be for the node with node id = `123` and which uses an URL argument named `SomeUrlArg` and with the value of that URL argument `456` (obviously, each node can have its own argument value).

To implement this, you would create a custom rule that looks like so:

* **Rules Event**: Drupal is initializing (you must use this event, otherwise you're too late).
* **Rules Condition**: NOT (Check if the URL argument (=`SomeUrlArg`) is present and that its value matches the value of your `field_access_token`).

Note the **NOT** in this Rules Condition: you only want to perform the Rules Action below if either the argument is absent OR if its value doesn't match with the `field_access_token` value.

To be able to specify these Rules Conditions, you can use the Rules URL argument module. For more details about this module, refer to my answer to "How to use Rules to redirect a user based on URL argument?".
* **Rules Action**: perform a redirect to whatever relative path that fits your needs (but not to `/node/123` of course).
> 1 votes

---
Tags: users
---


# Question
Title: When I update my database schema with drush entity-updates. I get an error
When I try to update my database Schema I'm getting the following error:

> Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException:\[error\] The SQL storage cannot change the schema for an existing field (order\_total in uc\_order entity) with data. in Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema-\>updateSharedTableSchema() (line 1376 of /www/htdocs/xxx/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php). Failed: \[error\] Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException: !message in Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema-\>updateSharedTableSchema() (line 1376 of /www/htdocs/xxx/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).

What can I do?

# Answer
Sounds like you are trying to update existing field order\_total in uc\_order. You can't update it since you have some data in it already. Remove content that uses it (orders), and try again.

Also note that drush entity:updates currently doesn't support all changes (e.g. changing table keys). See this Change Record for information on providing a hook\_update(): https://www.drupal.org/node/2554097
> 2 votes

# Answer
Have you been using ubercart for Drupal 8? There is a good chance give it's an alpha that there is no upgrade path. Using it in production at this stage could possibly cause issues when the schema for entities and tables change. Deleting the data on a production site might not always be an option.

If the data isn't relevant, a good way to "chase HEAD", that is follow the code when no upgrade path is available is to build sites as an install profile and regularly update your configuration objects as schema changes. Here is a blog post from a year or so before D8 was released which has some info about reinstalling to chase schema updates. More info on install profiles.
> 0 votes

---
Tags: database, drush, ubercart, updating
---


# Question
Title: Admin login returns 'Sorry, unrecognized username or password.'
When I attempt to login to my admin account, I'm getting a 'Sorry, unrecognized username or password.' message. The weird thing is that the password and username are correct. I've looked them up in the SQL database. I've even tried changing the password in the database, but have had no luck getting it to work. After every 5 attempts, I've had to use the `DELETE FROM 'flood';` sql command in order to reset the attempts.

In my local environment, I'm having no trouble logging in. This is also the first time I've attempted to login to the production website.

Is there anything I can try to fix this?

# Answer
> 3 votes
If you changed the password in the database, it won't work - the password in the database is hashed, so entering an un-hashed password means it will never work.

Use the password recovery tool to get a new password, or use Drush:

```
drush uli

```

Either of these will help you get your password.

# Answer
> 1 votes
If you have access to the server through SSH there are 2 ways to get in:

**With Drush**: execute the following command from the root of your Drupal installation, or from the website folder in a multisite installation:

```
drush uli

```

**Without Drush**: execute the following command from the root of your Drupal installation:

```
./scripts/password-hash.sh my_new_password

```

Where `my_new_password` must be replaced with the password you want for your user. This will give you the following response:

```
password: my_new_password hash: $S$DYx387nLkjxnMiupTv8ubxxnixbF3d0QchC2zhw7Y5XvlO6KqZ0T

```

This means that `$S$DYx387nLkjxnMiupTv8ubxxnixbF3d0QchC2zhw7Y5XvlO6KqZ0T` is a hashed version of the string `my_new_password` and it is the value you must add to your user in the database.

I'm not totally sure if a text hashed in this way but in a different Drupal installation (your localhost) would work... just check it.

Now, if you don't have SSH access, you can always use the `www.example.com/user/password` form to recover the password for your account. It will work if your server can send emails and you have access to the email account associated with the user you want to recover.

---
Tags: 7, users, database
---


# Question
Title: How to remove tag from SelectQuery object
I process `SelectQuery` object using `hook_query_TAG_after()` or `hook_query_alter()`.

I want to remove 'mytag' tag, which has been added as `$query->addTag('mytag')` somewhere else. Apparently, neither `SelectQuery`, nor `QueryAlterableInterface` has appropriate interface method.

Is there any means (besides `SelectQuery` subclassing) that I can use to remove a tag?

The reason may be the following (thanks Clive for asking):

I want to make a decision based on (expected) record set size inside `hook_query_TAG_after()`

I could do `$countQuery = $query->countQuery(); $total = $countQuery->execute()->fetchField()`

But, the cloned query will have same tag as original one and `execute()` will invoke the same hook ad infinitum.

# Answer
I still can not find a way to remove a tag from query, but I found solution for my case of count query. The idea is to use another tag to stop endless recursion:

```
function mymodule_query_mytag_alter(QueryAlterableInterface $query) {

  if ($query->hasTag('counted')) {
    return;
  }

  // Prepare count query
  $countQuery = $query->countQuery();
  $countQuery->addTag('counted'); // Abort hook recursion

  $tables =& $countQuery->getTables(); // Query may have sub-queries

  foreach ($tables as &$table) { // Tag all subqueries
    if ($table['table'] instanceof SelectQueryInterface) {
      $table['table']->addTag('counted'); // Abort hook recursion
    }
  }

  $total = $countQuery->execute()->fetchField(); // execute() will initiate recursion!

 // Rest of processing

}

```
> 1 votes

# Answer
You should use something like this:

```
    $new_query = clone($db_query);
    unset($new_query->alterTags['search_api_db_facets_base']);
    if (empty($new_query->alterTags)) {
      unset($new_query->alterTags);
    }
    $search_api_current_entities = $new_query->execute()->fetchAll();

```
> 0 votes

---
Tags: hooks, database
---


# Question
Title: Drupal 8 Views or Pixture Reloaded paging/formatting problem
Looks like I may have tripped over yet another bug in either Views or Pixture Reloaded in D8.

I created a view to show a simple content type I created called Newsletters. I can use the pager supplied by views to navigate to page 2 without a problem, but when I click page 3 or Next Page I get a screwed up display.

Excerpts from page 2 that displays properly.

Excerpts from page 3

View that I created.  Do you think this is a Views problem or a Pixture Reloaded problem?

# Answer
> 0 votes
Problem solved.

Looks like I had a corrupted instance of my Newsletter content type. When I deleted it the problem went away.

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


title: Display own unpublished nodes

text:
# Question
Title: Display own unpublished nodes
I tried creating a view where I display user's unpublished nodes.
The view works flawlessly for super user 1, but it doesn't work for authenticated users where no nodes are displayed though the authenticated user can directly access the unpublished node and edit it.
Things I tried:
1. Try different display formats (e.g. fields, full content)
2. Removed all kinds of filters
3. Removed all kinds of access rules for the view
4. Reviewed permissions:
a. Administer content is unchecked for authenticated user
b. View own unpublished content is checked for authenticated user
c. create/edit/delete content permissions are set for authenticated user
d. Bypass content access control unchecked for authenticated user

Is this normal or this is a views' bug?

UPDATE:
I posted my question on Drupal bug tracker. It seems that a module is causing the issue. https://www.drupal.org/node/2810077 I tried creating a new Drupal 8 installation with a view that shows unpublished content and now it displays all unpublished content regardless of user's permission...

# Answer
> 0 votes
Try view\_unpublished module and check can you see unpublished nodes.

> Description: This module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard.
>
> Additionally, using this module does not require any modifications to your existing URL structure.

---
Tags: views, 8
---


# Question
Title: How to select a shipping box for a particular product based on quantity using Drupal Commerce?
I have two shipping rules for a particular product.

Case 1. (Shipping box)

```
Quantity: 1-12
Width: 6
Height: 6
Length: 8.75
Weight: 3

```

Case 2. (Shipping box)

```
Quantity: 13-24
Width: 8
Height: 6.5
Length: 11.25
Weight: 4

```

When a user purchases this particular product, if the quantity below 12, use Case 1 shipping dimensions. If greater than 12, use Case 2.

Anyone can point out how to achieve this? I'm using Drupal Commerce with Commerce FedEx as shipping service.

There's a tutorial on how to achieve something like this but it uses flat rate and not any shipping box dimensions.

# Answer
Using the Commerce Box module, for which only a DEV version exists, you can create ***Commerce Box*** entities, but that's about it. E.g. it does not add any specific Rules Actions you can use to select the appropriate shipping box, such as based on product items and/or quantities.

However, there is an inspiring issue for the Commerce Fedex module, titled "Allow altering of default package dimensions". And comment nr 17 of that issue contains an interesting patch which allows for package dimensions alterations.
> 3 votes

---
Tags: 7, commerce
---


title: How I use fields on a custom template?

text:
# Question
Title: How I use fields on a custom template?
I'm attempting to build custom template for specific content type. So, I created `node--my-content-type.tpl.php` and tried to write some text: it works! Ok, now I want to render my fields. I have `$content['field_title']`, `field_author`, `field_cast` (is a field collection) etc.

I need values of these fields, so I tried to assign some variables: `$title = $content['field_title']['value']` etc, but it doesn't seem to work. I can only call render function to render these fields, but I want to format page in custom mode.

How can I get field info in order to use correct values? Thanks!

# Answer
Download and enable the devel module to use `dpm()` on `$content`. This will show you the proper structure of the `$content` array. Sometimes entities and fields will have different structures depending on their type or how they're being implemented for that content type.
> 1 votes

---
Tags: entities
---


title: How to test __get() in Node object?

text:
# Question
Title: How to test __get() in Node object?
I've created UnitTest based class for my service.

In one of my tested methods from service class I have code like:

```
if ($node->hasField('field_foo')) {
  $section = $node->field_foo->entity;
}

```

I've created mock for Node class and I know how to "emulate" hasField. However, how to mock this line:

```
$section = $node->field_foo->entity

```

I'd to set $section to be a Term object (or mock). Is this even possible? Now my test falls with an error:

> Trying to get property of non-object

but this is clear why. I'm using just mock, not real Node object.

# Answer
Yes, magic methods afaik can't be mocked.

You can use get('field\_foo')-\>entity which does exactly the same as \__get(), at least in this case. And then make that return a stdClass object with a -\>entity property. That's not exactly the same as what really happens, but it will work in the same way for your code.
> 0 votes

---
Tags: 8, testing
---


# Question
Title: How to use the path suffix in the Metatag page title?
My articles currently have a Metatag page title `[node:title]`. Sometimes this results in duplicate page titles (articles can have the same title), which isn't desirable from a SEO point of view. Therefore, I would like to add a number after `[node:title]` when there already exists an article with the same title.

I use the Pathauto module, which adds a suffix to duplicate paths, so this suffix would be perfect. Can I use the path suffix in the Metatag page title? Or is there another possible solution?

# Answer
> 0 votes
The only token Pathauto provides is `[node:url:args:join-path]`, the generated alias for the node. The suffix originates from, `pathauto_alias_uniquify(&$alias, $source, $langcode)`, which Pathauto doesn't expose in any way; it's generated as needed to ensure the output alias is unique.

Theoretically, you could provide your a custom token that tries to find the value, but it would be error prone; pathauto isn't storing the suffix independently so there's no guarantee that a matched value is actually the suffix generated from Pathauto.

This is more of an editorial problem then a technical one. So a better solution would be to enforce unique titles at an authoring level.

For example, utilizing the Unique Content Title module to verify that each node title is unique upon submission.

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


# Question
Title: Create imagefield and set min width and height programmatically
I've created an image field programmatically in Drupal 7. I want to set a minimum width and a minimum height on the image, so it checks whether the image is large enough.

The imagefield I've created:

```
$form['box_image'] = array(
    '#type' => 'media',
    '#title' => t('Image'),
    '#default_value' => isset($content['settings']['box_image']) ? $content['settings']['box_image'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'max_filesize' => '500 KB',
        'uri_scheme' => 'public',
        // Can I set the min width and height here?
      ),
    ),
);

```

Is this possible? Thanks.

# Answer
> 2 votes
Problem solved. If you use Media browser, like me you could use: `'min_resolution' => '750x500'`.

---
Tags: 7, media
---


# Question
Title: View with terms and if the're flagged or not on userpage
I want to make a subscription-page on the users-page. A user can flag terms. On the user-page there should

1) It's *no problem* to get a view with flagged content

* relationship Flags \[flag name\]
* contextual filter Flags: User uid

(see How to create view with user's flagged content?). The view shows only flagged terms.

2) It's *no problem* to get a view with flagged and not-flagged content

* relationship Flags \[flag name\] with current user & include only flagged content NOT checked
* path like /subscription

But as soon when i alter the path to user/%/subscribtion, every user can see other subscriptions by altering the path. When using this path with option 1), i see only flagged content (??). Removing the contextual filter, shows all content but accesible for everyone.

*How can i restrict the access to the own subscriptions, showing flagged and unflagged terms?*

# Answer
> 1 votes
Views only has 2 means to restrict access to Views: via a role or via a permission. Neither can help here so you'll have to use some other means to restrict the route path.

One way to go about this is to use the Views Access Callback module which was built for the purpose of dynamically checking access to a View. Once enabled, any module can implement `hook_views_access_callbacks()` to define a custom callback that can be used for permission checks.

It should be pretty easy to define a simple callback that inspects the current path to see if it belongs to the current user:

```
/**
 * Implementation of hook_views_access_callbacks().
 */
function MYMODULE_views_access_callbacks() {
  return array(
    'MYMODULE_access_account_subpages' => t('Access Account Subpages'),
  );
}

/**
 * Check that the user is the owner of the subpage.
 */
function MYMODULE_access_account_subpages($account = NULL) {
  global $user;
  return (arg(0) == 'user' && $user->uid == arg(1));
}

```

---
Tags: views, flags
---


# Question
Title: Drupal Commerce Kickstart 2 Adding Attrubutes to SPECIFIC Products
I have a product type and I sell a number of different items within that category, where most of them have the same 3 options (color, type, voltage). However, I have a couple of products of this type that don't conform to the same option set in that they have an one additional option for the customer to select.

The way I see it, I have two workarounds here, and neither of them seem like it's the "right" way to do it. Either I create a separate product/ variation type with all of the existing options, plus the additional option, or I add the additional option to ALL of my variations, even the ones that don't come with that option and just leave it blank for those products. Neither of these solutions are ideal in that it separates these products from others of their "type" or it creates the possibility for options to become available to the end user that are not possible.

Perhaps this is just me coming from an ubercart background, but I feel that I should be able to create an option that is specific to an individual product. I've scoured the internet and I'm not finding a way to do this, nor am I finding anyone else asking this question and getting an answer. What am I missing here?

# Answer
> 0 votes
I think you can use Conditional Fields module which can help you in showing and hiding fields based on any other field value.

You can also watch these tutorials in case you need to understand Drupal Commerce in detail.

---
Tags: commerce
---


# Question
Title: Accessing translation and language URL from hook_preprocess_menu()
I have setup language and translation in Drupal8 that affects my URL for example

```
myurl.com/ru
myurl.com/us
myurl.com/fr

```

What I need to do if find out which country is being accessed so I can add a variable to the twig theme layer

This is the hook that is working fine

```
/**
 * Implements hook_preprocess_HOOK() for menu.html.twig.
 */
function pnc_preprocess_menu(&$variables) {
    $code_to_access_language_url = 'this is a test';
    kint($variables);
    $variables['access_translation'] = $code_to_access_language_url;
    //print $code_to_access_language_url;exit;
}

```

I have found that under kint() there a lot of public methods for translation but I am not sure how I access them or which one to access. I know I could regex the url, but there has to be a cleaner way to do it?

# Answer
I found the answer myself.

```
if($variables['menu_name'] == 'navigation') {
  $langcode = \Drupal::languageManager()->getCurrentLanguage()->getName();
  // Add the logic here.
}

```
> 0 votes

---
Tags: theming, 8, hooks, i18n-l10n
---


# Question
Title: Any idea on how to include a an option in display handler in views
I want to include a check box below pager options i achieved it with form alter . The problem is how can i retrieve or store the value which user has selected and use that value for further process in views

# Answer
Since you want to add the configuration of the display (which is a plugin), you have two options:

1. Create a new display plugin
2. Change the class of the existing page plugin.

The two options are essentially the same, in the sense that you need to create a custom plugin class for views display. The only difference is if you alter what the plugin manager has stored or if you define a new one.

You should extend the existing `\Drupal\views\Plugin\views\display\Page` class.

Most of the stuff, you don't need to worry about, but you need to extend the following methods:

* defineOptions
* buildOptionsForm
* submitOptionsForm

A very simple implementation of a new plugin class (totally untested code, but should work with small alterations)

```
use Drupal\views\Plugin\views\display\Page

/**
 * Custom page display to add more options.
 *
 * @ViewsDisplay(
 *   id = "custom_page",
 *   title = @Translation("Custom Page"),
 *   help = @Translation("Display the view as a page, with a URL and menu links."),
 *   uses_menu_links = TRUE,
 *   uses_route = TRUE,
 *   contextual_links_locations = {"page"},
 *   theme = "views_view",
 *   admin = @Translation("Custom Page")
 * )
 */
class CustomPage extends Page {

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['custom'] = [
      'contains' => [
        'checkbox' => ['default' => FALSE],
      ],
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    // A bit tricky, since views uses a concept of sections. Either you need
    // to define your own section or you can just add your config to an existing
    // section. If you use an existing it will be a lot easier.
  }

 /**
   * {@inheritdoc}
   */
  public function submitOptionsForm(&$form, FormStateInterface $form_state) {
    parent::submitOptionsForm($form, $form_state);

    switch ($form_state->get('section')) {
      case '?':
        $values = $form_state->getValue('?');
        $this->setOption('custom', $values);
        break;
    }
  }
}

```
> 4 votes

# Answer
Simple way to achieve this job is using variables for acheive this job, as example your variable chould has this name "your\_views\_machine\_name\_myfeature" .

register a custom form submit halndler in for alter save your variable if checked with something like

```
$myvar = "your_views_machine_name_myfeature";
\Drupal::config('mymodule.settings')
      ->set($myvar, true)
      ->save();

```

and when you want just load it by

```
$value= \Drupal::config('mymodule.settings')->get('your_views_machine_name_myfeature');

```
> 0 votes

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


# Question
Title: How do I extract filename and filepath from a file field?
Here is what I am trying to tackle: I would like to allow a zip file to be uploaded via the default filefield upload widget for a content type. I am using hook\_node\_presave to take the zip file and extract is using a helper function based off of the core update manager. The error I am receiving is:

> Notice: Undefined index: filename in filefield\_unzip\_node\_presave() (line 18 of /sites/all/modules/filefield\_unzip/filefield\_unzip.module). Notice: Undefined index: uri in filefield\_unzip\_node\_presave() (line 19 of /sites/all/modules/filefield\_unzip/filefield\_unzip.module). Exception: Archivers can only operate on local files: \>not supported in archiver\_get\_archiver() (line 8149 of /include /common.inc).

Here is my code:

```
/**
* @file

* Allows uploading and extracting a zip file uploaded to a file field.
*/

/**
 *
 * Implementation of hook_node_presave($node)
 *
 */

function filefield_unzip_node_presave($node) {
if($node->type == 'game') {
    if (!empty($node->field_game_files)) {
        $zipFile = $node->field_game_files['und'][0]['filename'];
        $zipDirectory = $node->field_game_files['und'][0]['uri'];

        _filefield_unzip_archive_extract($zipFile, $zipDirectory);
    }
}
}

/**
 *
 * Copy of the function used by the update manager update_manager_archive_extract($file, $directory)
 *
 */

function _filefield_unzip_archive_extract($file, $directory) {
$archiver = archiver_get_archiver($file);
if (!$archiver) {
    throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $file)));
}

//Remove the directory if it exists, otherwise it might contain a mixture of old files mixed with new files (e.g. in cases where files
//were removed from a later release).
$files = $archiver->listContents();

//Unfortunately, we can only use the direct name to determine the project name. Some archivers list the first file as the directory (i.e., MODULE/)
//and others list an actual file (i.e., MODULE/README.TXT).
$project = strtok($files[0], '/\\');

$extract_location = $directory . '/' .$project;
if (file_exists($extract_location)) {
    file_unmanaged_delete_recursive($extract_location);
}

$archiver->extract($directory);
return $archiver;
}

```

# Answer
> 1 votes
> I found a solution to this, however stackexchange won't let me add an answer for 8 hours. I have it all typed out so if I forget to come back and upload it feel free to post on here to request the answer and remind me.

go on...

# Answer
> 1 votes
Okay, so after some additional digging I finally found the solution.

1) For the first two errors relating to undefined indexes...

It turns out that the entire file object is not loaded yet in hook\_node\_presave. This is why filename and uri are not defined. The only thing you can be sure has been set on the object at this point is the file's fid which is located in the file\_managed table in the database and references the specific fields table which contains the rest of the metadata. A good explanation for how to grab the file by its fid and load the entire thing along with its metadata into your script can be found here: Changing the file of a file field (drupal 7)

2) The second problem was just a misread on my part. When using the archiver\_get\_archiver function you need to supply the full path to the file, not just the filename in the $file paramater (I was under the impression that the path was included in the $directory parameter), and then for the $directory parameter you substitute the location you actually want the file to be unzipped to.

Please see below for the updated code:

```
<?php

/**
 * @file

 * Allows uploading and extracting a zip file uploaded to a file field.
 */

/**
 *
 * Implementation of hook_node_presave($node)
 *
 */

function filefield_unzip_node_presave($node) {
    if($node->type == 'game') {
    //get fid from file_managed table in the DB
    $fid = $node->field_game_files[$node->language][0]['fid'];
    //load the file associated with this fid
    $file = file_load($fid);

    //get the full path to the file
    $zipFile = $file->uri;
    //remove the filename from the directory
    $zipDirectory = dirname($file->uri);

    if (!empty($node->field_game_files)) {
        _filefield_unzip_archive_extract($zipFile, $zipDirectory);
    }
}
}

/**
 *
 * Copy of the function used by the update manager update_manager_archive_extract($file, $directory)
 *
 */

function _filefield_unzip_archive_extract($file, $directory) {
$archiver = archiver_get_archiver($file);
if (!$archiver) {
    throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $file)));
}

//Remove the directory if it exists, otherwise it might contain a mixture of old files mixed with new files (e.g. in cases where files
//were removed from a later release).
$files = $archiver->listContents();

//Unfortunately, we can only use the direct name to determine the project name. Some archivers list the first file as the directory (i.e., MODULE/)
//and others list an actual file (i.e., MODULE/README.TXT).
$project = strtok($files[0], '/\\');

$extract_location = $directory . '/' .$project;
if (file_exists($extract_location)) {
    file_unmanaged_delete_recursive($extract_location);
}

$archiver->extract($directory);
return $archiver;
}

```

# Answer
> 1 votes
Couldn't review your complete code, but you can alter and use below code to get file path,

`$imgpath = file_load($ifid)->uri;
print file_create_url($imgpath);`

hope it helps

---
Tags: 7, entities, hooks, files
---


# Question
Title: Create user accounts from a content type
I have Drupal 7 website. Initial requirement was to accept membership from public (anonymous users) without creating a user account. So the plan was to create a content type called ‘membership’ that has the fields Name, email address, mobile number, a unique alphanumeric ID and other fields for personal/professional details.

Now the requirement is changed and need to create a user account for each of this ‘membership’ type of content.

Is there any way to create user accounts from each of existing content of the type ‘Membership’ by fetching email id from the ‘email field’ and password from the ‘unique alphanumeric ID’ field (or some other means)?

# Answer
One solution is using VBO module, create a view with what content type you want ("membership") then perform a `run a PHP code` operation on them, and put something like this in Php code

```
$name = $entity->title; //fill it with what field you want
$email = $entity->YOUR_EMAIL_FIELD_MACHINE_NAME['und'][0]['value'];
$pass = $entity->YOUR_PASS_FIELD_MACHINE_NAME['und'][0]['value'];
$new_user = array(
  'name' => $name,
  'pass' => $pass, // note: do not use md5
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);

```

and another solution is create your custom Batch operation and try some thing like up snippet.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How do I override the vocabulary template but only on a specific content type
I have a vocabulary called "Sectors" and a content type called "News". Basically the vocab displays which sector the blog article is related to and links to the corresponding CMS page about that sector.

How do I customise the template that shows that vocabulary on my pages of that content type?

Many thanks.

# Answer
I think you can make that with views :)

You have to create your views with the fields you need. After that you will be able to theme them globally and locally. check views's theme suggestion

i hope it helped you
> 0 votes

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


# Question
Title: How to show thumbnails gallery images in the footer first section?
i have installed node gallery module as well media gallery but media gallery is not working for my drupal version now i am using node gallery but its show like below image

but i want like

# Answer
To do that you can use a views block to list all the pictures you want. After that you can use an image style to crop them like you want.

For the theming, feel free to use Views Theme Suggestion and Views Preprocess(ex : here) to add features et style images and content wrappers.

I hope it helped you.
> -1 votes

---
Tags: media
---


# Question
Title: What will happen if I delete 'page.tpl.php file'? Is there any alternative for this file?
I deleted page.tpl.php file from my current theme, and noticed that all content is still rendering in my Drupal site with a little difference in structure. What is the real use of this file? Can we have any alternative or a replacement for this file?

# Answer
page.tpl.php file is used to render your page body content (i.e. content inside `<body>` tag). Below is one line description of file on api.drupal.org.

> Default theme implementation to display a single Drupal page.

If Drupal is not able to find page.tpl.php file inside your theme, then it will use one of the following file:

1. If your theme has Parent theme, then Parent theme page.tpl.php file.
2. If no, file provided by system module.

If you're using version control system like GIT, Bitbucket, etc. you can revert your file from last commit. If not you will need to create new file and do necessary changes
> 9 votes

# Answer
All tpl are in /modules/system.

So if your theme miss one template, drupal take one of them inside this directory.
> 2 votes

# Answer
There are two things here

1. If you have a custom theme Drupal will take `page.tpl.php` file layout
2. Else it will render default drupal `page.tpl.php` layout.

It matters when you have a separate `page.tpl.php` file, Drupal will consider this layout.
> 1 votes

# Answer
The content would still be rendered because it uses the default template from Drupal core.

If you include (page.tpl.php) in your current theme folder, it would override the default (page.tpl.php) template.

Some useful links:

https://www.ostraining.com/blog/drupal/drupal-overrides

https://www.drupal.org/node/171194
> 1 votes

---
Tags: 7, theming
---


title: Import content to ckeditor correctly

text:
# Question
Title: Import content to ckeditor correctly
I imported large number of articles from another CMS to Drupal 8.

The content is in HTML and when i open a page i have html not interpreted.

How do i tell Drupal/Ckeditor that the content is in HTML ?

For now the only thing working is when i edit an article and clic on source twice to get the HTML interpreted but i can't do that to the large number of articles that i have.

# Answer
> 1 votes
It was simple after all in the table node\__body there is body\_format and you should set it to full-html

---
Tags: 8, wysiwyg
---


# Question
Title: How to add one another library files with different name from the theme name?
I try to define a separate library with different name from the theme name, according to this artcle:
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme
For example a library with below details:

* **Theme name:** MyThemeName
* **Library Name:** Library A
* **Library File Name:** libfile.info.yml

**libfile.libraries.yml**

```
LibraryA:
  version: 1.x
  css:
    theme:
      css/Style.css: {}

```

And then attach this library to all page in:

**MyThemeName.info.yml**

```
libraries:
  - MyThemeName/LibraryA

```

I would be happy to hear what the problem is, share your experiences and guide me to know what is the right way to add another library files with **different** name from the MyThemeName?
Thanks for any help.

# Answer
Short answer: You cannot.

Looking answer: The purpose to for the libraries file is too define **all** the libraries of a **module** / **theme**.

The file is recognized because it is has the name of the theme/module it is placed at.

If you want libraries with a different namespace then you will need to search for an alter hook, and define these libraries there (not recommended).
> 2 votes

# Answer
You're reading the module docs, the theme docs are here. The advice is identical for both though:

> To define one or more (asset) libraries, add a \*.libraries.yml file to your theme folder. (If your theme is named fluffiness, then the file name should be fluffiness.libraries.yml).

So if your theme is named MyThemeName, the libraries file should be named MyThemeName.libraries.yml, not libfile.libraries.yml
> 1 votes

---
Tags: 8, theming
---


title: How to add onclick event to a link?

text:
# Question
Title: How to add onclick event to a link?
I need to create a link, which when clicked should be able to set a session variable.

I have used l() function to create the link and tried this but this is not working.

```
'name' => l(t($n['name']),'edit_details',array('attributes' => array('onclick' =>$_SESSION['id']=$n['id'] ))),

```

# Answer
> 0 votes
Links do not allow any callback action, you can not set a variable on click event.

Instead you can either make it a custom form, where submit button is themed to look like a link instead of link and on form submission set the value in session.

Or other way would be, if its not secured information, you can pass it as query parameter in URL.

# Answer
> 0 votes
One easy way could be : Implement hook\_menu to provide a link to a function Then in function you can use any code you desire

something like this :

```
function yourmdoule_menu()
{
  $items['test/%'] = array(
    'title' => 'Some Function',
    'description' => 'Some function will be called by calling it',
    'page callback' => 'my_function',
    'type' => MENU_CALLBACK,
    'access callback' => true,
    'page arguments' => array(1),
  );
  return $items;
}

```

and then :

```
function my_function($id = 1){
  /// run every want you want
}

```

so now you can add a button with link to 'test/$nid' and it will call your desired function

# Answer
> 0 votes
You can do this modification: `'name' => l(t($n['name']),'edit_details',array('query' => array('new_id' => $n['id']))),`

And then, in your `edit_details` page PHP code you can add this:

```
$_SESSION['id'] = $_GET['new_id'];

```

If you don't have a module with PHP code for this page you can add a block, use the PHP filter and add the `$_SESSION` logic there.

---
Tags: 7, navigation, sessions
---


title: Can't load my template file

text:
# Question
Title: Can't load my template file
My `human.tpl.php` file is located in `/tpl` folder. Im trying to use `hook_theme` from the module:

```
    function human_theme($existing, $type, $theme, $path){
    return array(
        $item['human'] = array(
            'template' => 'human',
            'path' => drupal_get_path('module', 'human').'/tpl',
            'type' => 'theme',
            'variables' => array(),
        ),
    );
    return $item;
}

```

Why is this not working? I have some basic html code in my template file for testing purposes so it should show me something, but I get nothing back. If more information is needed, please let me know and I will add. Full code of a `.module` file can be found here.

# Answer
You have two returns (the second will never be hit). You have declared your array twice. It should be this:

```
function human_theme($existing, $type, $theme, $path){
  return array(
    'human' => array(
      'template' => 'human',
      'path' => drupal_get_path('module', 'human').'/tpl',
      'type' => 'theme',
      'variables' => array(),
    ),
  );
}

```
> 1 votes

# Answer
In order for Drupal to find these new template files specified in hook\_theme() you have to also clear the theme cache.

Also look into theme debugging for Drupal which will show you theme suggestions that show which template files are being used to generate sections of a page.
> 0 votes

# Answer
Thank you for all the answers, I used all of your suggestions, but the problem was with `_page()` function. After going through multiple examples I realized that I have to return `$render_array`, so now my `human_page` function looks like this:

```
function human_page(){
    //LOAD CUSTOM CONTENT TYPE FROM DB
    $result = entity_load('node', false, array('type' => 'human'));

    $render_array = array(
        '#theme' => 'human',
        '#items' => $result,
        '#title' =>t('ARGUMENT'),
    );
    return $render_array;
}

```

Lesson learned: Don't return simple variables in a page function because it will not work :)
> 0 votes

---
Tags: 7, theming
---


# Question
Title: CSS not updating with aggregation turned off
I'm running into an issue that I'm not sure how to diagnose. I'm working on minor CSS updates on a custom zen theme for a Drupal 7 site. I have the dev site set up on a laptop running ubuntu dev server. I have gone to performance and turned off css and js aggregation and flushed all the caches via Drush. The problem I'm having is that my css changes are being saved to the styles.css file, but they're not reflected when I refresh the site. Poking around in inspector, the css files have a `?oegwy2` suffix, which suggests that something is still aggregating or modifying the files. I'm not sure what that would be, I didn't set up sass for the this project, so the sass recompiling isn't likely what's going on here.

# Answer
Your CSS file may still be being cached, even if not aggregated. You can refresh the `?oegwy2` querystring with drush

```
drush cc css-js

```

Which refreshes the config variable: `css_js_query_string`

You could also add the following to your dev env settings.php to disable that querystring var:

```
$conf['css_js_query_string'] = '';

```

Then you should be able to just use hard reload (e.g Shift+Refresh) to refresh the CSS.
> 2 votes

---
Tags: 7, css-js-aggregation
---


# Question
Title: How to send author an email after they post content?
When I user saves a piece of "my\_custom\_content\_type" I want to send the user an email, basically "your content has been submitted, will be published after review" I know this is a core feature for webforms, but what is the best way to accomplish this for Custom Content Types?

# Answer
One easy way to do that is with the Rules module

* Event: After saving new content
* Action: Send email.

Here's an example Rules export (for `article`) that can be imported via the UI at `admin/config/workflow/rules/reaction/import`

```
{ "rules_review_notification" : {
    "LABEL" : "Send review notification email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "mail" : {
          "to" : [ "node:author:mail" ],
          "subject" : "[Notification] Content submitted for review",
          "message" : "Your content has been submitted and will be published after review."
        }
      }
    ]
  }
}

```
> 6 votes

---
Tags: emails
---


# Question
Title: How to replace usage of static Entity::load method calls for better testability?
In my method that I'm testing in UnitTestCase based class I have a statement:

```
Term::load(self::HARDCODED_TID);

```

Any other way to load Term object to make it 'mockable'?

# Answer
My workaround is (without changing legacy code):

```
   $entityManager = $this->getMockBuilder('\Drupal\Core\Entity\EntityManager')
      ->disableOriginalConstructor()
      ->getMock();

    $entityManager->expects($this->any())
      ->method('getEntityTypeFromClass')
      ->will($this->returnCallback(function ($class_name) {
        return $class_name == 'Drupal\taxonomy\Entity\Term' ? 'taxonomy_term' : '';
      }));

    $term = $this->getMockBuilder('Drupal\taxonomy\Entity\Term')
      ->disableOriginalConstructor()
      ->getMock();

    $termStorage = $this->getMockBuilder('\Drupal\taxonomy\TermStorage')
      ->disableOriginalConstructor()
      ->getMock();

    $termStorage->expects($this->any())
      ->method('load')
      ->willReturn($term);

    $this->termStorage = $termStorage;

    $entityManager->expects($this->any())
      ->method('getStorage')
      ->will($this->returnCallback(function ($type) {
        return $type == 'taxonomy_term' ? $this->termStorage : NULL;
      }));

    $this->container = new ContainerBuilder();
    $this->container->set('entity.manager', $entityManager);
    \Drupal::setContainer($this->container);

```
> 0 votes

---
Tags: 8, testing
---


# Question
Title: How to attach external js to Drupal.behaviours
If we write js code in Drupal.behaviours like below

```
(function($) {
  Drupal.behaviors.my_module = {
    attach : function(context, settings) {

}
};
})(jQuery);

```

that code will be execute multiple times on a page if needed even after an ajax callback.

But in the `preprocess_node` I have added an external js file. The problem is on node page there is a view with an ajax pager. When I move to next page through views ajax pager(`views infinite pager`) then that external js did not work.

So my question is, Is there a way to add the external js to Drupal.behaviours?

# Answer
> 0 votes
You can use `.once` available in Drupal.

```
Drupal.behaviors.Newsletter = {
    attach: function (context, settings) {
      $('#cd-sso-newsletter-form').once('form-Newsletter', function () {
        // Your Code.

        });
      });
    }
  };

```

# Answer
> 0 votes
Normally external libraries add functionality to the website but you have to code some JS to make it work. But sometimes, the library also executes something automatically if you add a specific class to a HTML tag. And this is what must be happening to you.

You are adding the external library and it is being executed in your HTML tags that are rendered from the beginning, but not in those that are added later through ajax.

But it shouldn't be a problem for you to execute the library function again for your specific new items in a custom Drupal.behaviors function. The external JS library is already loaded, so you just have to add its functionality to the new item in the way:

```
    (function($) {
      Drupal.behaviors.my_module = {
        attach : function(context, settings) {
           $(".my_new_item_selector").once('to-be-executed-once', function () {
             $(this).externalLibraryFunction();
           });
        }
      };
    })(jQuery);

```

---
Tags: 7, javascript
---


# Question
Title: What is standard approach to module development?
I'm using module to create content types and views I need.

* I prepare the content type in admin, then use export to export the configuration (i.e. `views.view.my_view_name.yml`, etc).
* Then I copy relevant pieces of configuration to the `mymodule/config/install` directory.
* I installed the module and it added the content type.

Now I had to update the content type's field display.

* So I changed it in admin and exported.
* Copied the updated file to my module.

Now I need to let Drupal know that my module is changed and to "reload" it.

* Clearing cache did not help.
* Calling `/update.php` said "nothing to update".
* Only thing that actually worked is disable/re-enable the the module. But in that process it breaks all the nodes that used the content type in the module (because for some time the content type was unavailable and therefore it "downgraded" it to normal node).

What is a standard way to develop modules? Removing the module after every change seems ridiculous.

# Answer
I think this post may be helpful to you:

https://www.mediacurrent.com/blog/registering-migrations-drupal-8

When developing migration configs, you need to update the configs, and it's difficult to get the changes within the install folder to re-register, so there are some scripts you can use, and there are some example drush commands.

Basically you can edit the configs with

```
$editable = \Drupal::configFactory()->getEditable($config_name);

```

And you can reinstall configs with

```
\Drupal::service('config.installer')->installDefaultConfig('module', $module_name);

```

I'd take a look at the code in /core/lib/Drupal/Core/Config/ConfigInstaller.php in the installDefaultConfig function. You could probably use part of that code to update just the config you need to update without touching the parts that should stay the same.
> 2 votes

---
Tags: 8, importing-exporting
---


# Question
Title: Get list of available options in a select field of custom content type
I created a custom content type called 'slide' that has a custom select field called 'field\_category'. I would like to be able to load the available options of 'field\_category' into the select field of a block form.

I'm currently attempting to follow the instructions of an answer to a similar question here but I'm still having trouble.

I'm grabbing the content type definitions like so

```
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'slide');

```

However when I spit out

```
print_r($definitions->getFieldDefinition('field_category'))

```

I can't actually find any of the options to grab. Is there a way to grab the available options of a field of a custom content type programmatically?

# Answer
```
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'slide');
$definition = $definitions['field_category'];
$settings = $definition->getSettings();
$allowed_values = $settings['allowed_values'];

```
> 7 votes

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


# Question
Title: Where is the autocomplete function for user/addressfield/autocomplete?
I searched but I cannot find the autocomplete function for addressfield module. The path of this autocomplete function is user/addressfield/autocomplete.

So I need the file that declare this function. Thanks!

# Answer
> -1 votes
I was using the Commerce Admin Order Advanced module. This is was providing the autocomplete.

---
Tags: 7, entities
---


# Question
Title: Saving file upload destination as private
I have a content type with a file field where I want the files to be private... I set the upload destination to private, but when the field instance is saved with features, this setting is not saved. How can I save this for use with an installation profile? (all other content types use public files)

# Answer
> 1 votes
The upload destination is not saved with the field instance, but with the field base. I was using an existing file field that was public. I needed to create a new field and define it as private and save that field base in my feature.

---
Tags: files
---


# Question
Title: How to configure programmatically a unique constraint on several fields of a custom entity?
How could I configure a unique constraint on several fields of a custom entity I have already created with drupalconsole.

The purpose is not allowing insert of two record of the same entity having for example same lastname and fisrtname.

# Answer
As suggested by elstevenson, I used the validation API.

Here the steps.

1. Create a repository in your module repo. /src/Plugin/Validation/Constraint
2. Create a constraint (name = Unique)

```
namespace Drupal\module_name\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;

/**
* @Constraint(
*   id = "Unique",
*   label = @Translation("Unique ", context = "Validation"),
*   type = "entity:entity_name"`
* )
*/

class UniqueConstraint extends Constraint {
   public $message= 'Unique entity!';
   }

```
3. Create a constraintValidator, and we populate the validate method with an entity query to make sure that there is no record having the same value of field1 and field 2:

```
 namespace Drupal\module_name\Plugin\Validation\Constraint;
 use Symfony\Component\Validator\Constraint;
 use Symfony\Component\Validator\ConstraintValidator;

class UniqueConstraintValidator extends ConstraintValidator {

/**
 * {@inheritdoc}
 */
public function validate($entity, Constraint $constraint) {
 $field1 = $entity->field1->value;
 $field2 = $entity->field2->value;
 $entity_type_id = $entity->getEntityTypeId();
 $value_taken = (bool) \Drupal::entityQuery($entity_type_id)
  ->condition('field1',  $field1)
  ->condition('field2',  $field2)
  ->range(0, 1)
  ->count()
  ->execute();
if ($value_taken)
{
$this->context->addViolation($constraint->message);

}

```

} }
4. Then configure our constraint in our entity (annotations part):

/\**

```
* Defines the entity_name entity.

*

    * @ingroup entity_name
    *
    * @ContentEntityType(
    *   id = "entity_name",
    *   label = @Translation("entity_name"),
    *   handlers = {
    *     ...
    *     "form" = {
    *     ..
    *     },
    *  ....
    *
    *   constraints = {
    *     "Unique" = {}
    *   }
    * )
    */

```
4. Then you should uninstall your module and then reinstall it . (if your entity is populated with data, you have to delete all the date).
5. In your code (for example in your form) , you have to ensure the validation :

```
$violations = $entity->validate();
if ($violations->count() > 0)
{
 $violation = $violations[0];

 drupal_set_message($violation->getMessage(),'warning');
}

```

Hope it will help.
> 3 votes

# Answer
I asked something similar a little while ago: How do I do a 'required if other field = x' using the entity validation api?

Basically, you want to use the Entity Validation API to create a Validation Plugin for your form.
> 1 votes

---
Tags: 8, entities, console
---