title: Redirect in multidomain sites

text:
# Question
Title: Redirect in multidomain sites
**My story is:**

I use module Domain Access for Multi domain feature and Internationalization, Domain Variable for the multilingual features. I have these domains:

* www.domain-a.com (main domain)
* www.domain-b.com
* www.domain-c.com

All is set to use www. prefix.

Now I have www.domain-d.com.au replacing www.domain-c.com. So I delete www.domain-c.com from Domain list in Drupal and add www.domain-d.com.au.

I also set redirect. So when user visit www.domain-c.com or domain-c.com, they'll redirected to www.domain-d.com.au. I add a rule in .htaccess:

```
RewriteCond %{HTTP_HOST} ^www.domain-c.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^domain-c.com$ [NC]
RewriteRule ^(.*)$ http://www.domain-d.com.au/$1 [L,R=301,NC]

```

**Result is:**

1. Visit www.domain-d.com.au. Page opened OK.
2. Visit domain-d.com.au, redirected to www.domain-d.com.au
3. Visit www.domain-c.com, redirected to www.domain-d.com.au
4. Visit domain-c.com, not redirected (fail).

**Question is:**

How to make domain-c.com to redirect to www.domain-d.com.au? Is here something wrong with my .htaccess.

I uncomment the with `www.` prefix in Drupal .htaccess and add the rule right below the

```
...

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

...

```

# Answer
> 0 votes
You have domain aliases with Domain Access, so you can edit your www.domain-d.com.au domain and add aliases that you need with redirection rule.

When you edit the domain you'll notice Aliases tab, there you can find explanation how to create the pattern and you just add the pattern that you need.

So, you don't need .htaccess for this.

---
Tags: .htaccess, domain-access
---


# Question
Title: How to change transition to fade on Boostrap Carousel module?
I have a boostrap carrousel view that works fine, but the slide show only has one option, tansition in milliseconds.

How can I change the transition to fade instead of slide? I've looked at the css code but it keeps moving, so hard to know what to change, additionally, it seems to be getting the css from boostrap.min.css ...

Site is at:

www.xuzo.com
carousel on home page

# Answer
you could do that with CSS transitions so it can be done easily without any Javascript.

The CSS:

```
.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}

```

I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.

Very smooth.
> 2 votes

# Answer
you can use CSS transitions like the example below,

```
.carousel-inner .item {
  left: 0 !important;
  -webkit-transition: opacity .4s; /*adjust timing here */
     -moz-transition: opacity .4s;
       -o-transition: opacity .4s;
          transition: opacity .4s;
}

/* Fade controls with items */
.carousel-inner .item.next.left,
.carousel-inner .item.prev.right {
    opacity: 1;
    z-index: 1;
}
.carousel-inner .item.active.left,
.carousel-inner .item.active.right {
    opacity: 0;
    z-index: 2;
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: Does anyone know how to add this in twig template, or in .theme?
I want this to be converted as a twig functions where can I pass a node id to the functions and display the node information such as link, content body, and image itself.

```
$nid = 1;
$node = node_load($nid);
$output = field_view_field('node', $node, 'field_foo');

// $output is a render array, so it needs to be rendered first
print render($output);

```

# Answer
> 2 votes
You can use Twig Tweak to render nodes/entities, and views.

> Twig Tweak module provides a Twig extension with some useful functions and filters that can improve development experience.
>
> ```
> {# You can load an entity from the current route. #}
>   <dt>Entity from route:</dt>
>   <dd>{{ drupal_entity('node', null, 'teaser') }}<dd>
>
> {# You can pass arguments to the view if needed. #}
>   <dt>View:</dt>
>   <dd>{{ drupal_view('view_name', 'page_1') }}<dd>
>
> ```

---
Tags: theming, 8
---


# Question
Title: How do I overwrite the view output for each vocabulary?
This is the Drupal 8 version of the following question: How do I override a taxonomy/term/% list with a view?

In short: You can edit the default, global taxonomy/term/% view, but you can not set custom taxonomy view. For example, /my-custom-category/% will show the default, global view output (not the customized one).

As you can see, the most elegant solution for Drupal 7 was using the *Taxonomy Display* module. However, it hasn't been ported.

How would you tackle this problem in Drupal 8?

# Answer
> 3 votes
Ok, it seems that I have found a solution. A Drupal 8 & 7 module called "Taxonomy Views Integrator" provides ability to set custom view for each vocabulary and/or terms. So far seems to work fine. Link to module - https://www.drupal.org/project/tvi

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


# Question
Title: Recaptcha not working in user register form
I am using google recaptcha in drupal 7 for user registration. The captcha works fine in the normal user register page but doesn't appear in the pop up dialog box for user registration?

some more info:

* i created the pop register form using ajax
* i checked the css of the site and the `<div>` of the captcha is present but doesn't have any content inside it like when it does when it is working.

# Answer
After some browsing, i found the Patch for the Recaptcha module that enables it to be used in ajax register form.

Please find the link to the node here

Cheers.
> 3 votes

---
Tags: 7, ajax, forms, captcha
---


# Question
Title: Restrict the node local tabs access to specific content types
I have a `module_name.links.tasks.yml` file for Drupal 8, whose content is the following one.

```
entity.node.module_admin:
  route_name: module_name.admin
  base_route: entity.node.canonical
  title: Admin Page
  weight: 99

entity.node.check_backend:
  route_name: module_name.check-backend
  base_route: entity.node.canonical
  title: Check Backend
  weight: 100

entity.node.download_webagent:
  route_name: module_name.download_webagent
  base_route: entity.node.canonical
  title: Download Webagent.conf
  weight: 101

entity.node.download_httpdconf:
  route_name: module_name.download_httpdconf
  base_route: entity.node.canonical
  title: Download httpd.conf
  weight: 102

```

These tabs appear in all the content type nodes. How can I restrict them to specific content types?

# Answer
Yes, routing is correct. Routes specify access rules, if you want your route to only be accessible for a certain node type, implement custom access callback and check for that.

The local task will then automatically respect that.

Example from core:

```
comment.reply:
  path: '/comment/reply/{entity_type}/{entity}/{field_name}/{pid}'
  defaults:
    _controller: '\Drupal\comment\Controller\CommentController::getReplyForm'
    _title: 'Add new comment'
    pid: ~
  requirements:
    _custom_access: '\Drupal\comment\Controller\CommentController::replyFormAccess'

```

That method then can receive the same arguments as the controller/form, in your case the node (just add NodeInterface $node) and you can check the type there and everything else you want (like permissions)
> 6 votes

# Answer
I found the answer !

I have to give like following in `module_name.routing.yml` which will inherit the entity node tabs which are defined in `local.links.task.yml`

```
module_name.admin:
  path: '/node/{node}/module_name'
  defaults:
    _controller: '\Drupal\module_name\Controller\MyController::my_function'
    _title: 'Admin Page'
  requirements:
    _permission: 'access admin tab'
    _custom_access: '\Drupal\module_name\Controller\MyController::admin_tab_access'

```

and in the controller function i am filtering the node types which are only i wanted to display in tab :

```
public function admin_tab_access($node) {
        $node_data = node_load($node);
        if(isset($node_data->field_p_type[0]->value)) {
            $node_type = $node_data->field_p_type[0]->value;
            if ($node_type == 'type_1' || $node_type == 'type_2'){
                return AccessResult::allowed();
            } else {
                return AccessResult::forbidden();
            }
        }
      return AccessResult::forbidden();
    }

```
> 2 votes

---
Tags: nodes, 8, navigation
---


# Question
Title: How to remove custom module provided entity instances by the time the module being uninstalled?
I have the following use case:

1. I have a custom module, which defines a custom entity type.
2. The custom entity type has some content in the database.
3. Module needs to be uninstalled now, but it can't, since "There is content for the entity type" (which is true, there is content)
4. How to extend the uninstall process of the module to first remove all the content instances and then do the rest?

I tried `hook_uninstall`, but that didn't help. Any ideas? Content can't be uninstalled by hand! (bigger project issue)

# Answer
> 2 votes
A potential duplicate.

The short answer (as I can see), you **CAN'T** **right now** remove content by the time you uninstalling the module. That makes you (us) to do it in two steps:

1. Write a `update_hook` where you remove all the content of the custom entity
2. You uninstall the module. (drush cex, which removes the module from
core.extension.yml)

---
Tags: 8, entities, installation
---


# Question
Title: How do I change the default value for a filter?
I want to customize the default value for a filter in view through some custom code. I have tried the below answer and its not working for me.

```
if ($form['#id'] == 'MY_EXPOSED_FORM_ID') {
// Modifications go here.
// example: (change the field name to yours)
// $form['field_adv_cat_1_tid']['#default_value'] = 'All';

```

}

How to change views exposed filter default value

And I tried these settings also.

```
$form_state['input']['field_program_tid'] = '44';
$view->filter['field_program_tid']->value = "44";
$view->exposed_input['field_program_tid'] = "44";

```

Anyone help me in this?

# Answer
you can try using hook\_form\_alter in your custom module.

```
     function yourmodule_name_form_alter(&$form,&$form_state,$form_id){
//print $form_id to get correct id of the exposed form
    if($form_id == 'views_exposed_form'){
      $form['field_program_tid']['#default_value'] = '44';
//you can unset "all" if you don't need it
      unset($form['field_width_value']['#options']['All']);

     }
    }

```
> 2 votes

---
Tags: 7, views
---


title: Dependency Injection while Unit Testing

text:
# Question
Title: Dependency Injection while Unit Testing
Normally with Drupal 8 I can use dependency injection like this:

```
<?php

class ExampleController extends ControllerBase {

  private $http_client;

  public function __construct(HttpClient $http_client) {
    $this->http_client = $http_client;
  }

  public function create(ContainerInterface $container) {
    $http_client = $container->get('http_client');
  }

  public function getResource() {
     $response = $this->http_client->get('http://biebertunes.com?q=selena');
     return $response->getBody();
  }

}

```

I can then use the $http\_client property's methods.

Now in my testing class I'm already extending the UnitTestCase class, so I don't have access to the create method for dependency injection.

```
<?php

class ExampleTest extends UnitTestCase {
  public function testGetResource() {
    $mock = $this->getMock('\Drupal\Example\ExampleController');
  }
}

```

Now when I run my unit tests it complains that I don't have the $http\_client parameter. So how can I inject $http\_client into the unit test without the create method?

# Answer
I have few thoughts about this situation:

1. Controllers should not contain business logic, services should. Therefor unit testing a controller is not a good idea in the first place.
2. If you are unit testing your controllers "getResource" method, why do mock the controller itself? You should mock the HttpClient. (that's the strong part of DI)
3. First you mock the classes which your constructor needs as arguments. Then you just create your object, which will you test like this: $example\_controller = new ExampleController($http\_client\_mock); And that's it.
> 4 votes

---
Tags: 8, testing, dependency-injection
---


title: The administrator menu disappeared

text:
# Question
Title: The administrator menu disappeared
I added the following code in my .htaccess file :

```
<IfModule mod_headers.c>
  Header set Set-Cookie HttpOnly;Secure
  Header always set X-XSS-Protection "1; mode=block"
  Header always set X-Content-Type-Options "nosniff"
  Header always set X-Frame-Options "DENY"
  Header set Content-Security-Policy "script-src 'self' https://apis.google.com"
  Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
</IfModule>

```

and the Administrator menu drupal no longer appear on my site. When I delete this line, the menu reappears. How to solve this problem ?

```
Header set Content-Security-Policy "script-src 'self' https://apis.google.com"

```

# Answer
Check with the styles/css hiding the administrator menu. style-src is script-src’s counterpart for stylesheets.
> 0 votes

---
Tags: commerce, security, .htaccess
---


title: How to close and start sessions?

text:
# Question
Title: How to close and start sessions?
How do i port following D7 code to D8?

```
  drupal_save_session(FALSE);
  session_write_close();
  drupal_save_session(TRUE);

  ini_set('session.cookie_lifetime', $cookie_lifetime);

  drupal_session_started(FALSE);
  drupal_session_initialize();

```

**Note**: I need to automatically logout user after `$cookie_lifetime` (say 30 sec).

I tried following code

```
$session_manager = \Drupal::service('session_manager');
$session_manager->save(FALSE);
session_write_close();
$session_manager->save(TRUE);
ini_set('session.cookie_lifetime', $cookie_lifetime);

$session_manager->setOptions(array('cookie_lifetime' => $cookie_lifetime));

$session_manager->start();

$session_manager->isStarted();

$session_manager->regenerate();

```

# Answer
My working piece of code:

```
$session_manager = \Drupal::service('session_manager');

$session_manager->setOptions(array('cookie_lifetime' => $cookie_lifetime));

// Force-start a session.
$session_manager->start();
// Check whether a session has been started.
$session_manager->isStarted();
// Migrate the current session from anonymous to authenticated (or vice-versa).
$session_manager->regenerate();

```
> 0 votes

# Answer
Calling user\_logout (Drupal 8) will do the trick. This essentially calls `$session_manager->destroy();` as well as invoking other hooks. The user\_logout function also redirected the user in Drupal 7 making it an undesirable programmatic approach, but this has changed.

```
// Call this one liner if you like simplicity and depending on services existing on the
// container.
user_logout();

```

If you want to manually do what user\_logout does you can inject the `session_manager`, `logger.factory`, `module_handler` services into your class and call similar methods.

```
  $user = \Drupal::currentUser();

  // Log some stuff.
  $logger_factory->get('my_module')->notice('User logged out, BAM!');

  // Make sure other modules can clean up after the user!
  $module_handler->invokeAll('user_logout'), [$user]);

  // Destroys the session and removes all cookies.
  $session_manager->destroy();

  // Sets up the anonymous user.
  $user->setAccount(new AnonymousUserSession());

  // And I guess if you will do something else with that anonymous user other than ending
  // the request, then start up and save a session. I don't think you need to do this and I
  // am not sure why you are saving cookie_lifetime on the new anonmyous session.
  // $session_manager->start();
  // $session_manager->setOptions(['cookie_lifetime' => $cookie_lifetime]);
  // $session_manager->save();

```
> 2 votes

---
Tags: 8, sessions
---


# Question
Title: How to Group the same content into one in View?
I am using Date Module to display the view summary for a particular year and also count the contents are created in the same year.

I have created the several contents in the year of 2016 , it may contain more than 12 contents.

In each content, I have created the DATE field in the format of (Day / Month)

And, I have called all the contents in the block , while clicking the link content , the content detail should be displayed in the page.

Help me to sort out this issue

# Answer
Look the Archive view /archive it will give you solution.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to display node add answer form on a question page using the Answers module?
I want to set up my own Q&A site. I've installed the Answers module. It has satisfied me mostly, but not entirely. I need to place an answer node add form on the question page. I have no idea how to do this. I tried hooks from dru.io/quieston but my hook does not work.

I tried Advanced form block and it is ok: it displays node add form in question page but answers need to have a relationship to their question. When I add an answer on a page `/node/add/answer` it does not allow me to add an answer without question id.

So to place an answer, the relative path should be like this: `/node/add/answer/117` \- where `117` is the node id of the related question. And when I create answer using an Advanced form block form, it really adds a new node, but such answer is not displaying in the question page and has an empty body. Because of question id should be defined.

How to display node add form in other node page with entity reference? And to define question id for this form?

# Answer
> 0 votes
The most recent version of the Answers module (= 7.x-4.0-rc2) already comes, out-of-the-box, with a "***answer node add form on the question page***" (as in your question). So you don't need any other modules, such as Advanced form block (it all happens automagically).

To experience it yourself, try out a demo of it. Here are the steps to do so:

* Head over to the demo site.
* Just accept the defaults to create a sandbox demo site (hit the create sandbox button, and wait for the process to complete).
* Login to the site (using the suggested defaults).
* Create at least 1 question using either the "*Add content*" menu link and then selecting "Question", or just enter relative path `/node/add/question`. And complete the title and body of the question.
* After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
* If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
* Use the ***Questions*** tab (or enter relative path `/questions`, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

**Note**: you may also want to enable the ***Answers Theme*** (sub-module of Answers, new as of 7.x-4.x). After you do, return to the question you created before, and see how the look-and-feel of both the question and related answer(s) below it changed ... Here is a sample screenprint of it:

---
Tags: nodes, 7
---


# Question
Title: Which table stores the content type fields?
I have a content type in drupal 8 and which table stores the content type fields and type in drupal 8 ? `Unlike in drupal 6` (in which there will be tables specifically for content types) like `content_type_contenttypename` its not creating the table and fields . Where will be these fields and data types stored in drupal 8 ??

# Answer
> 12 votes
Drupal 8:

* Content type = Bundle
* Node = Entity
* Base fields are in one table: `[entity]_field_data`
* Bundle fields are in seperate tables: `[entity]__field_name`

Bundle fields are stored in the same table for all bundles of one entity and can be shared between bundles of the same entity but not with another entity.

# Answer
> 2 votes
Each field values will be stored in a separate table.

For field foo the table name will be node\__foo

---
Tags: nodes, 8, entities, database
---


title: Creating a workflow

text:
# Question
Title: Creating a workflow
I'm learning drupal, I create a web form for duty travel that the user submitted. Now I want to create a workflow so after submitted the webform should be sent to manager for validation or cancelling after that he add some comments and files and resend it to the user

# Answer
You can setup complete workflow using these modules with webform:

Webform Workflow

> This is a Drupal 7 module which allows assigning workflow 'states' to webform submissions. Users can be notified when submissions change state. Permissions can be set to control access to submissions based on their state. The states themselves are fieldable Drupal entities.

Workflow

> workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state. You can set up the Workflow to alter states from form, page, comment, a special block, and a special workflow tab. Additionally, the submodule Workflow Access allows you to manage view/edit/delete permissions for content types per User role and Workflow state.
>
> Transitions between workflow states can have actions assigned to them. In our example, we could assign an action so that when the story moves from the Draft state to the Review state an email is sent out. Another action could be assigned to the transition from Review to Published so that the node's status is set to Published
> 2 votes

# Answer
You can use hooks to change almost anything in the webform like additional submit handlers can be handled, validation can be done, elements can be added, etc.

Refer the already existing answers, it will be helpful.

https://stackoverflow.com/questions/26174165/drupal-7-webform-submit-hook

Webform - Submit values from Drupal 7 from to external url
> 2 votes

---
Tags: webforms, workflows
---


# Question
Title: Is there a more performant alternative than overriding template files?
I've got to get rid of a lot of unnecessary markup in a view. In general, I accomplish that by overriding the template files in my theme, but this time the view is really huge and performance is going down. So I wondered, if there's a more performant way to reduce markup? When altering the markup of a node, than preprocess functions are faster then overriding template files, is there an analogical mechanism for views?

Edit 1: Sure, the reason for the weak performance is not the overriding of template files on the first place, but if I can optimize a bit there, I'll have to do that. In addition I regularily get into trouble by disabling markup in views UI itself: disableing row-styles for example is ignored when I use an Omega subtheme …

Edit 2: I am aware of the possibilities inside the Views UI; What I am looking for is a manual way with fine control.

# Answer
You can eliminate unnecessary markup through the Views UI.

When you add a field, hidden under Style Settings, they always have this default unnecessary checkmark

Also, you can remove more markup here

and here
> 8 votes

# Answer
It is *sometimes* more performant with View to display content instead of fields. This is best leveraged with custom view modes, where you configure the view mode to show the fields you want. You can then make the display of that view mode whatever you want via templates and formatters. This tends to work well when you have Entitycache.

That said, all systems are different. True profiling is really the best way to figure out what is taking time. Personally, I don't think that the views markup is adding any significant *time* to execution.
> 7 votes

# Answer
> the reason for the weak performance is not the overriding of template files on the first place, but if I can optimize a bit there, I'll have to do that

Sounds like you are being encouraged to prematurely optimize. If the view is suffering performance problems make sure caching is enabled on the view to avoid rendering the HTML from scratch as much as possible. That will provide a far larger boost to performance than almost any reduction in the number of files involved in the rendering process.

Once the theme registry is built having lots of overridden templates shouldn't be a noticeable hit on performance over using the defaults since Drupal is still loading a similar number of files (I have seen an exception to this if you create a file for every possible override in the entire chain, so don't do that).

If you switch to an entity display instead of a field display you *may* be able to reduce the number of templates loaded and therefore get a *minor* improvement in render speed. That assumes the entity display also takes steps to avoid field-level templates and/or is likely cached elsewhere already. Likely this would be a lot of expensive human labor for very little improvement in machine performance.
> 7 votes

---
Tags: views, theming
---


title: No navigation links on 404 pages

text:
# Question
Title: No navigation links on 404 pages
When I visit a page that does not exist, I expect to still see the primary and secondary links as on any other page, but what I get is no navigation links in the 404 page. See also No navigation links on 404 pages.

I have found a solution, but I am happy if something else can fix this (possibly without using extra modules).

# Answer
You can do it by defining a page in a custom module.

Create a page for the category "Page not found" using `hook_menu()`.

```
function MODULE_menu() {
  $items['page-not-found'] = array(
    'title' => '',
    'page callback' => 'MODULE_page_not_found',
    'access callback' => TRUE,
  );
  return $items;
}

function MODULE_page_not_found() {
  drupal_set_title('Page not found');
  $cust_err = "";
  $cust_err = $cust_err . "The requested page " . current_path() . " could not be found";
  return $cust_err;
}

```

The page callback uses `current_path()` to return the path of the page causing the 404 error.

Go to *Admin \> Config \> System \> Site-information*, and enter **page-not-found** (same name as defined in `hook_menu`) under *Default 404 (not found) page*.

Now the error page appears like in the following screenshot.

It is clear that it contains all the navigation links, and also the page URL producing the error (very similar to the original page not found). And the module mentioned in the answer above by @Nikhil will output "The requested page could not be found." but does not contain the URL of the page causing the error.
> 14 votes

# Answer
There is a module to make this work 404 Navigation

> On 404 Not Found error pages, Drupal will skip rendering of all the navigation links of your website for performance reasons\*. Some of these include:
>
> The "Primary links" block and any other menu links block. The Primary links and Secondary links of your theme. * Unless you have configured a "Default 404 (not found) page" on admin/config/system/site-information.

Also there is a Patch to fix this in D7.

In D8 See THIS Also THIS
> 11 votes

# Answer
There are also good module alternatives:

* Search 404
> Instead of showing a standard "404 Page not found", this module performs a search on the keywords in the URL, e.g. if a user goes to http://example.com/does/not/exist, this module will do a search for "does not exist" and shows the result of the search instead of the 404 page. This should help retain visitors coming in from old URLs linked from other sites or from search indices.
* Fast 404

> Drupal has expensive 404 errors. On an 'average' site with an 'average' module load, you can be looking at 60-100MB of memory being consumed on your server to deliver a 404. Consider a page with a bad .gif link and a missing .css file. That page will generate 2 404s along with the actual load of the page. You are most likely looking at 180MB of memory to server that page rather than the 60MB it should take.
> 6 votes

# Answer
You can do it by defining a page in a custom module.

Create a page for the category "Page not found" using hook\_menu().

```
 function MODULE_menu() {
   $items['page-not-found'] = array(
     'title' => '',
     'page callback' => 'MODULE_page_not_found',
     'access callback' => TRUE,
   );
   return $items;
 }

 function MODULE_page_not_found() {
   drupal_set_title('Page not found');
   $cust_err = "";
   $cust_err = $cust_err . "The requested page " . current_path() . " ould not be found";
   return $cust_err;
 }

```

It's almost good. But this code returns:

> "The requested page page-not-found could not be found"

need change ***current\_path()*** to ***request\_uri()*** and will return:

> "The requested page /request\_uri could not be found"
> 3 votes

---
Tags: 7, navigation
---


# Question
Title: Ideas for notification of map events occurring in some user defined area?
I'm in charge of a full stack D8 (customer requirement) based project. It's mostly a Leaflet's web mapping application. The Leaflet part itself is almost done and it looks beautiful, fast and powerful. I let you know the URL once it gets released to the public.

Ahead comes a sprint ... This is the basic requirement of this phase:

1. The map is made of several, user switched feature layers.
2. Some of these layers receives regular updates, for instance: parties in the neighborhood announced witin the last week, two weeks and a month.
3. The 'parties' entity is stored in several mapserver endpoints (typically a REST service throwing GeoJSON out). Each period (week, two weeks, month) have its own endpoint.
4. Users (not Drupal users, subscribers only) draw an area in the map and 'subscribe' to the events announced on that area. By 'announced' I mean: points occurring within the user selected area.
5. At some specific time, my application is going to check the interesting points in the user defined area to send that out to the subscriber.

I forecast lots of challenges here. This is what I came up with to this very moment:

1. Create a content type with at least an email field and geofield support to store the points of the location area drawn by the user and her email (sort of a 'subscription backend').
2. Compose a new view to expose these subscriptions in some serialized fashion.
3. Code a helper script (bash, php, python) that is going to consume this D8 view and get the updated data from the mapserver endpoint.
4. Using cron and possibly Message Stack (yeah, yeah, I know, still in dev for D8...) to deliver the message for the final recipient.

This is an example of the entire use case:

http://fires.globalforestwatch.org/map/

In the right toolbox, look for the exclamation sign icon. This is the alert function of that map. Draw a line, enter your email and bang!

There are lots of other requirements for this use case (mobile friendly html emails, screenshots of the map with the 'parties' points and previously drawn area overlaid and such), but for know I'm concerned only with the most basic functionality: to store subscribers, their location of interest and how to transform this in some useful data for their mailboxes.

So, what are your thoughts? Anybody out there already faced this task? Any tips?

I don't need code (nor rejects if you wish). Any insights on a elegant way to get things done right? Oh, the less 3rd party modules, the better. Core ones are ok.

**EDIT:** the new Courier module (D8 only) just came to my attention. It looks like a good contender to Message Stack in the message delivery front.

# Answer
> 1 votes
I've managed to find a solution for this one by myself. Here's how I did it.

## Step 1: New Subscription and Notification

1. Create a content type for 'alerts'. This content type features fields like: title (composed by first + last name), first name, last name, email address, alert type (party or police, for instance), status (inactive, optin, optout), plain text (no D8 Geofield module required) with two fields to store map bounding boxes, geocode name, geocode ID and subscription key.
2. I've implemented a UI dialog in the map that interacts with the user (so she inputs a geocode search or a map draw) and the 'headless' D8.
3. By using the wonderful D8's RESTful Web Services module, that dialog implements code to POST user input data to the alerts content type. This code is smart enough to deal with subscriptions from a geocode search or user draw, as their requirements are a bit different. It also handles form field validation according to certain business rules, takes care of the verification key generation and forwards the request via Ajax to an external, custom made email verification script.
4. The custom made email verification script (not a D8 module, just plain PHP code with PHPMailer lib) receives the request and resolves the query string sent there. This guy takes care of query string values validation to the very same set of business rules applied to the form. If everything is fine, an email with the requested data is composed and sent to the user by using a secure SMTP. If there are errors in the query string validation (e.g. user is trying to bypass the form or fake someone), it returns with the validation step error code. At this point, the dialog in 3 above redraws itself to let the user know what have just happened (success or error code translated into human readable language).
5. All fine up to this point, the dialog code in 3 effectively POST the new alert content and email is sent to the user. This email displays The Big Red Button™ saying something like 'Verify Now!' When a user click (or tap) on it, the second step in the process begins...

## Step 2: Subscription Validation

Another custom made, plain PHP script (also totally apart of D8) is called by the last user action from the above step. This scripts also counts on D8 RESTfull powers, the amazing (Guzzle PHP HTTP Client) (\*3) to perform various actions related to subscription activation. Here they are:

1. 'Click Here To Verify' call the activation scripts with some query string (e.g. D8 node id and verification key). These are first and foremost validated do the same set of business rules we had before. Looks good? Move on. Fake? Redirect to a nice error page.
2. A (Guzzle client) (\*4) is set with enough options to make it run smooth and secure, '(cookies =\> true) (\*5)' is among then.
3. A (POST request to login) (\*6) is fired. I've created a **special user and a role** just for D8's API usage. This is to prevent sneakers from the outside. Also, by having a custom made script, I can rest assured the it is always calling on localhost (127.0.0.1), so the Ops guys could set all sort of firewall, proxies and CORS rules to backend protection.
4. We're in, GET D8's (CSFR token) (\*7) for the session.
5. (GET node content) (\*8) and retrieve just the information we need to verify (e.g. status, verification key and such).
6. Perform validation logic. Fine? Move on. Fake? Redirect to a nice error page.
7. (PATCH node) (\*9) to update the signature status.
8. (GET logout) (\*10) to finish the session, close the Guzzle client by adding header `headers => [cookies => true]` in this request, and some further cleanup magic.
9. All set? Redirect user to a nice success page. Something went wrong? Catch exception and redirect to an error page.

During the whole runtime of the script, a specially crafted debug stream and a try/catch carefully listens to any exceptions. When debug is enabled, the page redirection is hold and debug information shows up so the Ops could inspect what is going on behind the scenes.

Well, it doesn't stop there. There are still the optout and the subscription delivery features. However, the above works pretty well as a base for all the remaining steps.

For the sake of completeness to the OP question, the above looks pretty elegant to me (i.e. decoupled, maintainable, secure) and uses no 3rd party D8 modules at all, just the core ones. As a plus, the custom scripts are implement relying on well maintained, open source projects.

**For moderators:**

Please add the URLs bellow to the places their belong in the text above to as I'm in lack of reputation to do so.

```
*3 http://guzzlephp.org/
*4 http://docs.guzzlephp.org/en/latest/quickstart.html#making-a-request
*5 http://docs.guzzlephp.org/en/latest/quickstart.html#cookies
*6 http://dropbucket.org/node/6743
*7 https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AcsrfToken/8.1.x
*8 https://www.drupal.org/documentation/modules/rest/get
*9 https://www.drupal.org/documentation/modules/rest/patch
*10 https://www.drupal.org/documentation/modules/rest/javascript

```

---
Tags: users, 8, notifications
---


# Question
Title: Change part of theme according to time of day
In Drupal 8, I'm trying to change part of a twig template according to time of day.

For instance, if in one of my twig templates I have:

```
<img src="img_during_the_day.jpg"/>

```

Where and what do I need to change to have it produce

```
<img src="img_during_the_day.jpg"/>
<!-- or -->
<img src="img_during_the_night.jpg"/>

```

according to server time?

I was thinking of doing it passing a variable to my twig template and then something like:

```
{{ if (variable == 'day') }}
    <img src="img_during_the_day.jpg"/>
{{ else }}
    <img src="img_during_the_night.jpg"/>
{{ endif }}

```

But I don't know how to pass a `$variable` to the template. Also, if I were to do this in a module, what `hook` would I have to alter to achieve this?

The idea would be to use PHP's `date` object to find out the current time to then change the value of a certain `$variable` in a hook, and said variable would be available to work in twig with in the above pseudo-syntax.

Can anyone share some pointers on where to begin?

# Answer
You can define new variables in the array `$variables` in preprocess.

Assuming this is the page template:

**modules/mymodule/mymodule.module:**

```
function mymodule_preprocess_page(&$variables) {
  if ( ... ) {
    $variables['daynight'] = 'day';
  }
  else {
    $variables['daynight'] = 'night';
  }
}

```

Then use the variable in your twig code:

```
{{ if (daynight == 'day') }}
    <img src="img_during_the_day.jpg"/>
{{ else }}
    <img src="img_during_the_night.jpg"/>
{{ endif }}

```

Or shorter:

```
<img src="img_during_the_{{ daynight }}.jpg"/>

```

You will get some problems with caching. In drupal and in proxies and browsers. So this is probably not a server but a client side solution.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How do i run the equivalent of single configuration import from a hook?
I have a hook\_update\_N that is changing a field. It is deleting the field and recreating it with the same name but a different field, formatter, and widget.

The problem I'm having is that there is a view that is using my field and when I delete my field the view is being deleted and my site then throws an error.

I have the views.view.view\_name.yml file saved in a directory. Is there a function or set of functions that will import the view from that file?

# Answer
> 0 votes
```
 if (\Drupal::moduleHandler()->moduleExists('views') && !View::load('view_name')) {
    $config_path = DRUPAL_ROOT.'/configurationpathto/views_view_view_name.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('views.view.view_name')->setData($data)->save(TRUE);
  }

```

---
Tags: views, 8, importing-exporting, configuration
---


# Question
Title: Getting error for drush site-install :Unable to find a matching SQL Class
I have created a drupal project using composer:

```
composer create-project drupal-composer/drupal-project:8.x-dev ./ --stability dev -vv

```

Then I downloaded drush using this command:

```
composer global require drush/drush

```

Now I try to install the drupal site using this drush command:

```
drush si standard --db-url=mysql://***:***@localhost/recommande_db --site-name=***** --account-name=*** --account-pass=*** --account-mail=*****

```

I'm getting this error:

```
exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL Class. Drush cannot find your[error]

database connection details.' in

/Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/sql/sql.drush.inc:588

Stack trace:

#0 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/sql/sql.drush.inc(573):

drush_sql_get_class(Array)

#1

/Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/core/site_install.drush.inc(117):

drush_sql_get_class()

#2 [internal function]: drush_core_pre_site_install('standard')

#3 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(366):

call_user_func_array('drush_core_pre_...', Array)

#4 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(217):

_drush_invoke_hooks(Array, Array)

#5 [internal function]: drush_command('standard')

#6 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(185):

call_user_func_array('drush_command', Array)

#7 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67):

drush_dispatch(Array)

#8 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/preflight.inc(66):

Drush\Boot\BaseBoot->bootstrap_and_dispatch()

#9 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/drush.php(12): drush_main()

#10 {main}

```

I tried all the suggestions found in several forum but no solution. Can you help please!

For your information here the result of the "drush status" command:

```
PHP executable         :  /usr/bin/php

 PHP configuration      :

 PHP OS                 :  Darwin

 Drush script           :  /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendo

                           r/drush/drush/drush.php

 Drush version          :  8.1.2

 Drush temp directory   :  /tmp

 Drush configuration    :

 Drush alias files      :

```

# Answer
> 1 votes
Make sure that you execute drush from the web folder.

---
Tags: drush, composer
---


# Question
Title: Content Translation : Language filter not available in views
I use a view to show a list of nodes flagged by a global flag (any user, any language) and would like to return only current language related nodes.

For that I should be able to add a filter in the View which is something like "Content Translation: Language". However no such filter seems to be available. Any idea why this filter is missing?

# Answer
> 1 votes
To make the view results correspond to the language switcher, add a filter for **Content Translation: User's Current Language**, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

**If** no option for the '*User's Current Language*' is available in the filter criteria form, **then** verify your configuration at *Configuration -\> Languages -\> detection and selection*: the order should be 'URL, Default, User', and not something like 'Default, URL, User' (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Note: filtering Views results in a multi language site can sometimes be challenging, as illustrates also in discussions such as in https://groups.drupal.org/node/47478 ...

# Answer
> 3 votes
Between the filters you should see 'Content Translation: User's Current Language'. Also check out the Internationalization Views module for more translation options for views.

> Translate views using Internationalization. This is a work in progress and not all Views properties can be translated yet.
>
> This module has been moved from Internationalization package so we can have different branches compatible with each of the Views versions. Use the same branch of the Views version you are using (2.x. 3.x).

# Answer
> 0 votes
**It happens when you have Entity Translation enabled in parallel.**

The "Content Translation: Language" filter is missing from Views if you have enabled both Content Translation (module `translation`, in Drupal 7 Core) *and* Entity Translation (module `entity_translation`, a contrib project). There is also a this Views issue dealing with this situation, and there also the environment had both translation systems enabled.

This is normally not meaningful as these two systems are meant as alternatives to each other, with Entity Translation being the more modern one. However, in some special cases it can be meaningful (like, handling some legacy node types with Content Translation, new node types with Entity Translation).

**Solution alternatives:**

* **Use Select Translation.** This module is specifically made for Content Translation and provides a Views filter "Content Translation: Select translation" that provides the same possibilities as the missing "Content Translation: Language" one, plus more freedoms to configure fallback behaviour.
* **Disable Entity Translation.** This alternative should give you the "Content Translation: Language" filter with its fallback behaviour. Perhaps disabling is not enough though and you'll have to uninstall the `entity_translation` module as well (see here for a similar but reverse situation).
* **Use "Content: Language" (usually *not* applicable).** When Entity Translation is enabled, on its own or additionally, it provides a Views filter "Content: Language" (as also found by the OP). It provides the same configuration options as "Content Translation: Language" and can also filter nodes for which you use Content Translation. However, it does not know about the "translation set" concept of Content Translation, so the Views result can contain multiple translations of the same content (unlike when using it with Entity Translation nodes). For that reason, it is only a solution if you allow only one value to pass the filter, like by setting it to "Content: Language (= Current user's language)". Also unlike the "Content Translation: Language" filter, this filter does not provide a fallback to the site's default language.

---
Tags: 7, commerce, views, i18n-l10n, flags
---


# Question
Title: How to show, in a view, content depending on user language or default?
In one of my Views, showing a preview of some nodes, how can I set the nodes to be shown to be the ones in the user language or, if the user has no language set or is anonymous or the language is not set for the node, the ones in the site default languages?

I can do the two thing with 'filter criteria' separately but not together...

# Answer
> 2 votes
Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for **Content Translation: User's Current Language**, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the **User's Current Language** is available in the filter criteria form, then verify your configuration at *Configuration -\> Languages -\> detection and selection*: The order should be **URL, Default, User** and not something like **Default, URL, User** (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

**Notes**:

* The above may turn out to NOT be the complete answer. You may use the Entity Translation module and, in that case, there is not this option if you use it in 'entity' mode: if only some fields of the node are translatable the option is there but a bit more difficult to find. If you have the 'Body' of your nodes set to translatable entity then the option is "Body language" to be set to Current User Language.
* The Internationalizations Views module only has a **DEV** version for D7, but right now there are over 31K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because *+31K users can't be wrong*, right?

# Answer
> 0 votes
You can use the Select Translation module to configure language fallback behaviour for Views results.

This is esp. useful when the "Content Translation: Language" filter is not available, which is needed for @Pierre's solution. This happens when you have Entity Translation enabled in addition to Content Translation \[details\].

---
Tags: 7, views, i18n-l10n
---


# Question
Title: What may be causing "fails the check integrity"?
I need some help with the Rules `fails the check integrity` issue. I am running the Rules version 7.x-2.7. It works most of the times and appears to be suddenly.

When I checked on the dblog it has error message like so:

> the action Set a data value () fails the integrity check and cannot be executed

After clearing all the Drupal caches, it will start working again. It had a message like Action was marked dirty, but passes the integrity check now and is active again.

This is a screenprint of the issue.

# Answer
> 1 votes
### Possible reasons

***Some*** reasons (pretty sure it is an incomplete list ...) that may help to pinpoint the reason for this typical message are like so:

* Some module is missing "now" (which was there when the rule was added). It could well be a recently disabled, or uninstalled module.
* The rule (or Rules Component) refers (in a Rules Condition or Rules Action) to a machine name of a field that is "no longer there".
* The rule (or Rules Component) refers to a Rules Component that is no longer there, or, as a variation, something changed in a Rules Component (eg the data type of a parameter) so that it is no longer compatible with the way some Rule is trying to execute that Rules Component.
* The rule (or Rules Component) refers to a content type (or more generic an entity type) that is no longer there, or a role that was removed.
* The rule (or Rules Component) has a Rules Condition or Rules Action, which is provided by some module, based on some logic in that module. A good example of this can be found in the Content Access module: the ACL module seems to be a weak module dependency of the Content Access module, i.e. the Rules Action with machine name `content_access_action_user_grant` is only available if, and for as long as, ACL is enabled (if you disable the ACL module, then any rule that has such `content_access_action_user_grant` action will show such "*... fails the integrity check*".

### Possible resolutions

Depending on what the actual reason is, these are possible remedies for it:

* Re-enable recently disabled modules:

+ if any such module adds an extra content type with some related fields, and any of your rules still refer to them, then that would cause the typical error message.
    + if the existence of any such module is used to provide some extra Rules Condition or Rules Action, then any of your rules that still refer to those conditions/actions would cause the typical error message.
* If you know/remember which entity some field (which got deleted) referred to, then manually adding that field again (with identical machine name) should make the error message go away.
* ...

---
Tags: 7, rules
---


title: Search indexing slow query

text:
# Question
Title: Search indexing slow query
Drupal 7.x

The search module's indexing maintenance sql query takes a couple of minutes to complete each time cron gets triggered.

```
SELECT t.word AS realword, i.word FROM search_total t LEFT JOIN search_index i ON t.word = i.word WHERE i.word IS NULL`

```

Database search info data info:

127k nodes

37m search\_index

1.3m search\_total

Search settings: 100 Number of item to index per cron ron

Indexing settings: 2 Minimum word length to index

Search is only enabled for nodes and once indexed, searches are fairly fast. However the actual process of re-indexing takes it's toll in our database server. Do you guys have any suggestions on how to mitigate this problem caused by extremely large websites? How do large websites scale Drupal's built-in search functionality without using additional tools like solr, elatisticsearch, etc.? All indications I'm seeing is to probably throw more hardware at this problem.

# Answer
> 0 votes
1. Maybe you should use a Search API and Search API database module? It's more flexible in terms of working with index. For example, you can configure index settings(which fields to index)and rebuild index after it.
2. Try to use Google Custom Search module.

---
Tags: database, search, performance, cron
---


title: Conditionally increment a case ID

text:
# Question
Title: Conditionally increment a case ID
I have a table {cases} which has in part, `upload_id`, `case_id` `case_name` etc etc. With a custom form, users, depending on role(4 custom roles), will upload a file `upload_id`. This has been serialized. If it is a new case, *case\_name is NOT present* then get max(case\_id) add one and save to DB. Also users can add a file to existing cases, so the `upload_id` would auto-increase, and the `case_id` stays the same. I've been working on this one area for 2 weeks and have come to the end of my rope.

I have written all of this into a custom PHP web app a few years ago, but now I have to rewrite it all in Drupal 7. Any pointers in the right direction would be appreciated.

\**********EDIT\**************

I didn't think you could have 2 Serial Fields in the same table schema. I already have `upload_id` as a serial. I just can not figure out how to insert the case\_id in Drupal.

Real scenario:

User uploads the file, upload\_id =3796, case\_id = 2916, case\_name = 'xxx Macy'.

User forgot to include something needs to upload additional file. upload\_id = 3797, case\_id = 2916 where case\_name = 'xxx Macy'. And still forgot a file, upload\_id = 3798, case\_id = 2916.

New user uploads file, upload\_id = 3799, case\_id = 2917, case\_name = 'Jane Deer'.

# Answer
They way you describe your case\_id it sounds like the primary key of your table (a number which increases by 1 for each new entry). Rather than increasing this number in the form (and spare your self the trouble of assure atomic results when more than one person are entering cases at once) you can just set the column as primary key in your schema and let the db manage it. That way you don't need the field in your form at all.

```
$schema['case'] = array(
  'fields' => array(
    'case_id'       => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
   //your other fields
  ),

  'primary key' => array('case_id'),
);

```

---

That said I would consider not using a custom table to start with and instead leverage the functionality Drupal is shipped with and use a node to represent your cases.

There is a contrib module called Serial Field which allows you to add a field to your content type which increases by 1 for each case you create. There is a file field in core which allows you to upload a file to the site as well. The name field is a little tricky as Drupal doesn't allow empty titles but you can easily work around it by adding a simple text field for the name and generate the actual title with Automatic Entity Label.

In this case you need to download the two contrib modules, install them, create a case node type, add and configure the fields and you are done. The advantage is you can still leverage a great number of existing modules working with nodes/fields and entities which is much harder/impossible with custom tables. And you can display the results using Views.
> 2 votes

# Answer
It sounds as though you are trying to keep as much of the old PHP app that you wrote and just wrap Drupal around it. You will have much more success if you recreate the app in drupal and then use the migrate module to pull in all the existing data.

As for the data structures in drupal. I would consider using nodes for cases, and then use the file entity module to build more usefulness around the files. Then you can link the two entities together with and entity reference.
> 0 votes

---
Tags: 7, forms, database
---


# Question
Title: How to remove id="node-[nid]" with Display Suite?
How I can remove the node id when I override a node layout with Display Suite?

In some (old) how-to I noticed that the id node is not present when a node layout is overridden with DS.

i.e.: from this

```
<div id="node-1" class="ds-1col node node-page clearfix clearfix view-mode-full content clearfix" typeof="foaf:Document" about="/node/1">

```

to this

```
<div class="ds-1col node node-page clearfix clearfix view-mode-full content clearfix" typeof="foaf:Document" about="/node/1">

```

Thanks

# Answer
> 2 votes
Below code is quoted from template.php of Tao.

```
/**
 * Implementation of preprocess_node().
 */
function tao_preprocess_node(&$vars) {
  $vars['hook'] = 'node';

  $vars['classes_array'][] = 'clearfix';

  $vars['attributes_array']['id'] = "node-{$vars['node']->nid}";

  ...

```

The ID is added by this line.

`$vars['attributes_array']['id'] = "node-{$vars['node']->nid}";`

You can override it by implementing the same hook function in **template.php** of your custom child theme.

```
/**
 * Implements hook_preprocess_node().
 */
function mytheme_preprocess_node(&$vars) {
  unset($vars['attributes_array']['id']);
}

```

---
Tags: theming, nodes, hooks, display-suite
---


# Question
Title: Custom module administration page template not working
I've been trying to load a custom template for a custom module page in the administration section, but the template isn't being loaded. This is the code so far:

### custom\_theme.module

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

    $template_path = drupal_get_path('module', 'module_custom') . '/templates';

    $items['admin/module-custom'] = array(
        'title' => 'Turnos',
        'description' => 'Custom module functionality',
        'position' => 'right',
        'weight' => -15,
        'page callback' => 'system_admin_menu_block_page',
        'access arguments' => array('administer site configuration'),
        'file' => 'system.admin.inc',
        'file path' => drupal_get_path('module', 'system'),
    );

    $items['admin/module-custom/availability'] = array(
        'title' => 'Captación de disponibilidad',
        'description' => 'Users availability functionality',
        'page callback' => 'user_availabity',
        'access arguments' => array('administer site configuration'),
        'type' => MENU_NORMAL_ITEM,
    );

    return $items;

}

/**
 * Implements hook_theme()
 */
function module_custom_theme($existing, $type, $theme, $path) {

    $template_path = drupal_get_path('module', 'module_custom') . '/templates';

    return array(
        'user_availability' => array(
            'variables' => array('users', NULL),
            'template' => 'module-custom-admin',
            'path' => $template_path
        )
    );

}

/**
 * Load user availability
 */
function user_availabity() {

    $users = entity_load('user');
    return theme('user_availabity', $users);

}

```

### module-custom-admin.tpl.php

```
<div>
    <h2>Template subtitle</h2>
</div>
<div>
    <?php foreach ($users as $key => $user) : ?>
        <div>
            <?php print_r($user); ?>
        </div>
    <?php endforeach; ?>
</div>

```

But the template's code isn't shown:  Thanks for any advice.

# Answer
> 0 votes
`hook_theme` expect second parameter to be an array. See the doc here. In your implementation below you are passing an object.

```
/**
 * Load user availability
 */
function user_availabity() {

    $users = entity_load('user');
    return theme('user_availabity', $users);

}

```

What you can do is to typecast the value.

```
$users = (array) entity_load('user', array(uid));

```

Here is an example from my existing project.

```
/**
 * Implements hook_theme().
 */
function derusni_theme($existing, $type, $theme, $path){
  return array(
    'quotation_list' => array(
      'template' => 'quotation-list',
      'path' => $path . '/templates',
      'type' => 'theme',
      'variables' => array(),
    ),
  );
}

```

And here is function that implements that theme function.

```
/**
 * List the quotation started by user.
 */
function derusni_page_quotation_started() {
  $variables = array();

  $quotation_ids = _get_quotations(arg(1), 'Started');
  foreach ($quotation_ids as $quotation_id) {
    $variables['quotations'][] = entity_load_single('quotation', $quotation_id);
  }
  $variables['edit_path'] = "/admin/structure/entity-type/quotation/quotation/";
  $variables['dest_path'] = '?destination=/' . current_path();

  return theme('quotation_list', $variables);
}

```

HTH

# Answer
> 0 votes
It is a well known issue of the `hook_theme()` function.

For successfully loading the template file, you have to follow the naming convention to rename the template name, which must be same as the theme key, with converting `_` to `-`.

```
/**
 * Implements hook_theme()
 */
function module_custom_theme($existing, $type, $theme, $path) {

    $template_path = drupal_get_path('module', 'module_custom') . '/templates';

    return array(
        'user_availability' => array(
            'variables' => array('users', NULL),
            'template' => 'user-availability',
            'path' => $template_path
        )
    );

}

```

---
Tags: 7, theming
---


# Question
Title: Change Default Value of XML sitemap enable/disable flag
Is there a way to change the default value of a node's XML sitemap enable/disable flag for the XML sitemap module?

The default is disabled. I have a large old site that I want to have completely site-mapped by the module. The documentation I can find says I need to edit every node to enable -- there has to be an easier way.

Barring that, is there a Drush command available for it?

# Answer
You seem to be asking 2 things.

The default inclusion status for nodes is set on the node type's edit page (**admin/structure/types/manage/MYTYPE**). The XMLSiteMap settings are stored as `xmlsitemap_settings_node_MYTYPE` in keyed array (`status` key) if you'd rather `drush vset` the setting.

As for bulk inclusion, the `xmlsitemap` table stores all items index for inclusion/exclusion in your site map. A drush sqlq command can bulk update these settings.

```
#Set all XMLSiteMap node entries as included
drush sqlq 'UPDATE xmlsitemap SET `status` = 1 WHERE `type` = "node"'
drush xmlsitemap-rebuild

```
> 1 votes

---
Tags: drush, xml-sitemap
---


# Question
Title: Is there a list of file/image field subtokens?
Token browser does not show the options for file properties. \[node:file-field:0:file:url\] gets the url, but is there a list of all file options? Or is there a way to check it from sourcecode somehow?

Gathering the list:

* \[node:field-image:0:file:url\]
* \[node:field-image:0:file:extension\]
* \[node:field-image:0:file:name\]
* \[node:field-image:0:file:size\]
* \[node:field-image:0:file:mime\]
* The last thing that is still unknown to me is if there is an option to pull image width and height? If I remember correctly that data is in the db.

# Answer
# Using contrib module

Imagecache Token provides a list of token for image styles, which includes image width and height.

If you want to have those data of original image, you can create an image style `original` without adding any effect at `admin/config/media/image-styles/edit/original`

Now you can retrieve the image width and height with:

* `[node:field_image:original:width]`
* `[node:field_image:original:height]`

> **Downside**
>
> All images will be duplicated to the `original` image style folder.
> 2 votes

# Answer
For file https://www.drupal.org/node/390482#token-file https://www.drupal.org/project/imagefield\_tokens and add https://www.drupal.org/project/filefield\_paths add this module for {The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.}

Check this screenshot:
> 2 votes

---
Tags: 7, tokens, media, files
---


# Question
Title: Taxonomy term empty fields in a ALL vocabulary
I have this "screen" when I click on "manage fields" for all of my taxonomy vocabularies (new included):

All these "fields" empty. And I have no these fields.

# Answer
It's an issue caused by the Commerce Services module version 7.x-1.x-dev (25-Apr-2014): https://www.drupal.org/node/2024813
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to only define hook_menu path to certain URL
Consider this simple implementation of hook\_menu()

```
/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return "Hello World!";
}

```

This code work when I visit **example.com/hello**, but so does when I append extra argument to the url like **example.com/hello/world**. How do I only define the **example.com/hello** only without getting all these 'derivative' URL defined as well?

# Answer
> 3 votes
Per the `hook_menu()` docs:

> When path 'abc/def' is requested, no further path components are in the request, and no additional arguments are passed to the callback function (so $ghi and $jkl would take the default values as defined in the function signature). When 'abc/def/123/foo' is requested, $ghi will be '123' and $jkl will be 'foo'. Note that this automatic passing of optional path arguments applies only to page and theme callback functions.

In other words, it's a feature of the Drupal menu routing system to accept additional path components.

If you're looking to try to circumvent this, you can use an `access callback` function to enforce your sole path:

```
/**
 * implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => 'helloworld_callback',
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return "Hello World!";
}

/**
 * Access callback for /hello. 403 on addition path components.
 */
function helloworld_callback() {
  return (request_path() == 'hello');
}

```

---
Tags: 7, routes, hooks
---


# Question
Title: How to Create Membership Groups for Products?
I'm exploring if the latest release of Drupal Commerce (using Commerce Kickstart 7x-2.38) will work for my Apparel eCommerce requirements. We need membership to groups (which will be corporate accounts or schools) that will present authenticated users a selection of apparel products using corporate or school logos and of course special pricing. I've looked into both Organic Groups and Membership Entities and neither seem to be the best solution. Any ideas?

# Answer
Another alternative to look at is the Group module, which is an alternative to Organic groups ...

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

# Resources
> 0 votes

---
Tags: 7, commerce, organic-groups
---


# Question
Title: How to Setup Multilingual Section (Not Site)
I support an existing site that contains a multilingual section. We have a link to this section on the homepage and it just consists of some basic pages. Now I have been asked to incorporate one of our existing content types into this section (i.e. Content Type A - English, Content Type A - Spanish). The node/add form and the node display pages all need to be in Spanish. I also need to be prepared to support additional content types, additional languages, etc.

So I'm experimenting with the Locale and Internationalization modules. The problem I'm having is that it seems to be designed for an entire multilingual site. I need the site to remain an English site. For example, when an anonymous user creates a spanish node, the user is returned to homepage: www.example.com/es. The homepage is not going to be translated. User should be returned to www.example.com. I also noticed all of the links on www.example.com/es include the es prefix in the path.

Question(s): Is this the right approach to a multilingual section? If so, is there a way to configure Drupal to understand that www.example.com/es, www.example.com/es/mypage, etc. do not exist?

# Answer
> 1 votes
Yes you are right, internationalization is made for a full website in several languages. But you will be probably be able to achieve what you want by using views everywhere.

Instead of displaying a classical node, you will display a view with 1 node inside a block, inside a panel (probably). You setup your view to use the language your want and the content type you want, that should do the trick. It's a bit different approach if you compare it with the standard drupal approach of creating page.

To ensure that the node page is not accessible, you can use the module node page disabled.

I hope it helps

Cheers

---
Tags: i18n-l10n
---


# Question
Title: Add custom classes or theme a custom form
I have a custom form generated in a module.

I want to style the individual inputs by adding classes to them.

Can I add them through the `buildform()`?

```
public function buildForm(array $form, FormStateInterface $form_state) {
  //Return array of form API elements
  $form['location'] = array(
    '#type' => 'textfield',
    '#placeholder' => 'Enter your suburb or postcode...',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Go'),
  );
  return $form;
}

```

If yes, how would I do this? I can't seem to find a good reference for parameters that can be passed into the `$form` array.

Alternatively, is there a way to pass the elements to a theme template like can be done with custom blogs or controllers?

# Answer
You can add classes in `#attributes`:

```
$form['submit'] = array(
     '#type' => 'submit',
     '#value' => $this->t('Go'),
     '#attributes' => ['class' => ['button']],
);

```
> 4 votes

---
Tags: forms, 8
---


title: How to implement a store locator?

text:
# Question
Title: How to implement a store locator?
Is it possible to create with something similar to this store locator using Drupal?

# Answer
> 4 votes
Another option is the recently released Google Store Locator module on drupal.org. Some cool features: you can customize the map marker pins to be your own custom icon, and you can make the map 'location aware' which allows the user to share their location with the browser, and the map will re-center and zoom based on their location.

# Answer
> 2 votes
Yes, but it will be complex to set up. If you're using Drupal 7, you can create a "Store" content type with checkbox fields that store the various attributes (24-hour service, airport locations, etc.)

Then you can install the location module to assign a location to each store. You will need to enable the feature for converting the addresses you input into latitudes and longitudes.

Next, installing the gmap module will give you the ability to display Google maps.

For the search functionality, you can use views, for which there are many excellent tutorials online.

# Answer
> 2 votes
Check out OpenLayers locator that was just released, and that I maintain. It is a feature module that creates a robust, turn-key store locator using the Openlayers, Openlayers Proximity, Addressfield, Geofield and Geocoder modules.

# Answer
> 0 votes
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.

---
Tags: google-maps
---


# Question
Title: How to remove the Themekey module after its Installation failed?
I installed the module ThemeKey, but the installation failed with a WSOD. Now every page gives me the same 'The website encountered an unexpected error'.

So I need to remove themekey, but how can I do so? The watchdog table doesn't include any message relating to this problem, so is no help. Can I disable/remove it via the database, or am I stuck with rebuilding the whole system?

# Answer
Use Drush `drush pm-uninstall themekey` or Drupal Console `drupal module:uninstall themekey` to disable themekey from the command line.
> 2 votes

---
Tags: 8, installation
---


title: Converting UTF8 Data to SQL_ASCII

text:
# Question
Title: Converting UTF8 Data to SQL_ASCII
I want to convert my query results from a database, which is `SQL_ASCII` database encoded, to `UTF-8`.

```
$result = $query->execute;
$converted_data = array();
foreach($result as $record){
    $converted_data[count($converted_data)] = drupal_convert_to_utf8($record->name, 'sql-ascii');
}

```

I used `drupal_convert_to_utf8` but it returns blank all the time. I was confused if `sql-ascii` should be the second parameter of drupal\_convert\_to\_utf8. The database encoding, where the query results is fetched, is `SQL_ASCII` in `postgres`.

UPDATE:

According to the official documentation, It

> Requires the iconv, GNU recode or mbstring PHP extension.

What are they? Am I going to install/include it or what?

# Answer
> 2 votes
Go to `/admin/reports/status` and take a look at your unicode library. If you don't have multibyte support, install it: http://php.net/manual/en/mbstring.installation.php

I.e. for ubuntu like systems it's `sudo apt-get install php7.0-mbstring` for PHP7.

EDIT:

You could try 'auto' instead of 'sql\_ascii', and btw., you can skip the count() call and can just write `$converted_data[] = drupal_...`

END EDIT

---
Tags: 7, forms, database
---


# Question
Title: Having issue with multiple calls of same view
I am using the function views\_get\_view and it's working fine if am using this once in a function. But when I am calling this function multiple times with different arguments in the same function the result is going to lose. In that case, the result always be same as coming with first-time arguments. Following are my code.

```
 $viewname = "profile_match_with_job";
  $display_id = "block_3";
  $view = views_get_view($viewname);
  $view->set_display($display_id);
  $view->set_arguments(array(138,70)); // views Contextual filter parameters
  $view->pre_execute();
  $view->execute();
  $myresult =  $view->result;
// here $myresult array showing the correct result

```

But I am calling the same thing with dfferent argument then the result is not corrct like this

```
 $viewname = "profile_match_with_job";
  $display_id = "block_3";
  $view = views_get_view($viewname);
  $view->set_display($display_id);
  $view->set_arguments(array(138,80)); // views Contextual filter parameters
  $view->pre_execute();
  $view->execute();
  $myresult =  $view->result;
// here $myresult array showing the same result but in that case I have chnaged the param values from 138,70 to 138,80

```

# Answer
Yes, this issue arises because you have a current copy of view and you not destroy it. Kindly use below code for multiple use (suggested to be every-time).

```
$viewname = "profile_match_with_job";
$display_id = "block_3";
$view = views_get_view($viewname);
$view->set_display($display_id);|
$view->set_arguments(array(138,80)); // views Contextual filter parameters
$view->pre_execute();
$view->execute();
$myresult =  $view->result;
$view->destroy();

```
> 6 votes

---
Tags: views
---


# Question
Title: How to use Rules to change the value of entity reference’s field?
I have two content types (*Inventory* and *Sales*). In *Sales*, I referenced *Inventory* using the Entity reference module.

In *Inventory*, I have a stock\_available (integer) field. In *Sales*, I also have the same field, so that I can automatically populate its value from *Inventory* using the Entity reference autofill module.

When I add a new *Sales* node, I want to adjust the value of stock\_available in the referenced *Inventory*, so that gradually it becomes zero in the referenced *Inventory* node.

I know how to set value/calculated value from other filed within same content type, by using the Rules module.

I have no idea how I can do same things to targeted entity reference node. I think it's possible by just rule configuration. Please let me know if something needs to change to get same output that I expected.

# Answer
# Step 1: Create a Rules Component

Create a Rules Component (of type "action set") like so:

* Parameters are "`node`" and "`stock decrease`".
* Rules Action = "*set value/calculated value from other filed within same content type*" **(\*)**.

Here is a prototype of such Rules Component:

```
{ "rules_decrease_stock" : {
    "LABEL" : "Decrease Stock",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_to_update" : { "label" : "Node to be updated", "type" : "node" },
      "stock_decrease" : { "label" : "Stock decrease", "type" : "integer" }
    },
    "ACTION SET" : [
      { "drupal_message" : { "message" : "Something just got sold, so please decrease the stock for node with id [node-to-update:nid] with an amount of \r\n[stock-decrease:value] units. To actually do so, replace this (informational) Rules Action with setting the appropriate value for the appropriate field ..." } }
    ]
  }
}

```

The actual action only displays a Drupal message (to show the values of the variables passed to it). Replace that action with the actual update of your inventory node **(\*)**.

# Step 2: Create a Rule

Create a rule with Rules Event something like "after updating a node of content type "Sales". Maybe also some Rules Condition like "`stock_available`" is updated (checked if the unsaved value differs from the saved value). And add these Rules Actions:

* Update the `stock_available` in your Sales content type **(\*)**.
* Perform the Rules Component (from step 1), whereas you pass these 2 **parameters**:

+ the `node`, which you can pass via the value (token) of the entity reference.
    + the `stock decrease` amount (which is identical).

**(\*)**: you indicated in your question you know how to do that ...
> 0 votes

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


# Question
Title: How to get tid on behalf of node id (nid) in Drupal 8?
I am new in `Drupal 8`. I have created a node with `category (taxonomy)`. Now I don't understand how to get `tid` by using `nid`. I am using `$node->body->value` to get the body field value and use `{{ body }}`. But to get category id if I use `$node->field_category->value`, it will display `Null` in debugging mode.

```
function THEME_preprocess_node(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  $variables['body'] = $node->body->value;    // Working fine
  $cat_id = $node->field_category->value;    // Its showing null
  kint($cat_id);
}

```

So can anyone please tell me how can I get the `category id (tid)` of a node?

# Answer
A reference field doesn't have a property `value`. You can use `entity` to load the term or `target_id` to get the term id:

```
$tid = $node->field_tags->target_id;

```
> 3 votes

# Answer
You can loop over the items like this:

```
foreach ($node->field_category as $item) {
  $tids[] = $item->target_id;
}

```

or get the entities like this:

```
$terms = $node->get('field_category')->referencedEntities();

```
> 0 votes

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


title: Taxonomy URL Inside View

text:
# Question
Title: Taxonomy URL Inside View
I've created a View that displays all of my 'Product Category' taxonomies. I'd also like to get the path alias for each taxonomy listed. Usually to do this, I'll add a hidden 'Path' field, so I have access to it in my Twig template.

There doesn't seem to be that 'Path' field though, the closest I can find is 'Link to Taxonomy term' field. This isn't what I'm after though as this field seems to be preformatted, when all I want is an absolute URL. I've tried playing around with the rewrite rules of this field, but none of the changes seem to take affect.

Is there a way for me to convert the Term ID I have access to into my system path or path alias of my taxonomy pages? Is there a different way? Thanks in advance.

# Answer
Add the field `Taxonomy term: Term ID` to your list. On the settings of this field you have options for `Rewrite results` check the box `Output this field as a custom link` on the path option you can write it `taxonomy/term/{{ tid }}` and below to can check the box `Use absolute path` if you want too.

This will automatically convert the link into alias if it exists.
> 1 votes

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


title: Exposed Taxonomy field in views filters

text:
# Question
Title: Exposed Taxonomy field in views filters
I have a taxonomy field in my view in filters and I have made it exposed to the users with selection type "dropdown" along with "Show hierarchy in dropdown" as checked.

I'm also using Better Exposed Filters (BEF) module where in its settings I have selected the option to display the exposed filter as "nested checkboxes/radio buttons".

Also under more options in BEF's settings I have selected "Add nested all/none selection" so that if the parent taxonomy term is selected then all the child taxonomy terms should also get selected and vice versa. But this thing is not working properly, after selecting the parent term all the child terms are not getting selected neither after selecting all the child terms the parent term by default is getting selected.

Can anyone suggest ideas to make this work properly. Thanks In advance!!

# Answer
> 1 votes
Solved out with following jQuery code:-

```
$('.bef-tree input:checkbox').click(function() {
            var $this = $(this);
            if ($this.is(':checked')) {
            // Check all child checkboxes
            $this.closest('li').find('input:checkbox').prop('checked', true).change();

            // If all siblings are checked, the also check the parent term
                if ($this.closest('li').siblings('li').find('input:checkbox[checked="true"]').length
                == $this.closest('li').siblings('li').find('input:checkbox').length
                ) {
                    $this.closest('li').parent().closest('li').find('input:checkbox').prop('checked', true).change();
                }
            }
            else {
            // Uncheck all child checkboxes
                $this.closest('li').find('input:checkbox').prop('checked', false).change();

            // Uncheck all parent checkboxes of this element
                $this.parentsUntil('ul.bef-tree').filter('li').each(function() {
            // NOTE: "this" is no longer the closure variable, but the filtered
            //       li elements we selected and are iterating through.
                $(this).find('input:checkbox:first').prop('checked', false).change();
                });
            }
        });

```

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


title: Restrict views to specific languages

text:
# Question
Title: Restrict views to specific languages
Using the locale modul (core) and i18n it is possible to show a language switcher, which will guide the user to corresponding nodes in another language. In case of views, this language switcher points to a view in every language. The views path i.e.

www.website.com/path/to/view

gets "translated" to every language

www.website.com/language-path/path/to/view.

Is it possible to change this behaviour or to restrict the view to specific languages?

# Answer
> 3 votes
**If you want to map different URLs** corresponding to the same view in different languages, this answer will help you. Basically you have to enable "Translation sets" and "Path translation" modules, both part of i18n module. Then in `admin/config/regional/i18n_translation/path`, add the translated paths and then add a "translation set" which will map all these pages together.

**If you want to restrict the view to specific languages** because it yields no results for the other languages, you can filter your view results by the user's current language and set a "No results behaviour" to display the view results for a different (default) language, using a `Global: View area`. See this question for more details. Of course you can also display a specific node (404 page or other) as a "No results behaviour".

@jumper: I've put this answer in case you want to give the bounty :)

# Answer
> 2 votes
yes you can restrict the views language by adding filter criteria for content:language if you want to restrict it based on the content language or by user:language if you want to restrict/filter it based on the preferred language for the current logged user

# Answer
> 0 votes
**You can use Select Translation.**

If your view is meant to show nodes, and your nodes use the Content Translation\* mechanism, you can install the Select Translation module. It provides a filter "Content translation: Select translation" by which you can define a fallback mechanism to select which language version of results should be used.

For example, you can specify that if a result is not available in the current language, its English version is used. So if *no* results are available for the current language, as in your case, this is equivalent to visiting the English version of the view. So effectively this "restricts the view to specific languages" resp. "hides the view in specific languages" as you asked for.

**Content Translation:* That's the default translation mechanism in Drupal 7, available in Core. So if you did not install the alternative (Entity Translation), you are using this one.

# Answer
> 0 votes
**You can rewrite the language filter in custom code.**

I know you only want to modify the view if it has no content to show in the selected language. Here's a solution that can do that, but also allows you to modify the view results *even if* there are results in the currently selected language:

1. Add a language filter to your view:

* If you use Entity Translation, add the "Content: Language" filter.
    * If you use Content Translation, add the "Content Translation: Language" filter.
    * If you use Content Translation and want automatic language fallback behaviour for each result, you can use the "Content translation: Select translation" filter instead, provided by the Select Translation module.
2. Implement `hook_views_query_alter()` and change the parameters of your language filter as needed. For details, see this answer. For example, you can implement logic such as "If the current language is Chinese, set the language filter to show English content".

---
Tags: 7, views, i18n-l10n
---


# Question
Title: Why a successful migration is showing (0 created, 0 updated, 0 failed, 0 ignored)?
I have written a custom Migration tp import redirects (D7 -\> D7).

Everything is working fine. Imports were successful, rollbacks are working fine etc.

However, I am getting `Processed XXXX (0 created, 0 updated, 0 failed, 0 ignored) in XX seconds (XXXXX/min)` message after import.

Why is not showing the number of items created?

Is there a method in destination plugin or migration where I need to return this count or return TRUE/FALSE for each row processed or something like that?

# Answer
> 0 votes
Got answer!!

I missed the following code from the `abstract class MigrateDestination`:

```
/**
 * Maintain stats on the number of destination objects created or updated.
 *
 * @var int
 */
protected $numCreated = 0;
public function getCreated() {
  return $this->numCreated;
}
protected $numUpdated = 0;
public function getUpdated() {
  return $this->numUpdated;
}

```

These variables need to be updated during the import process and need to be defined/updated in class that is extending the `MigrateDestination`.

---
Tags: 7, migrations
---


# Question
Title: When to use different vocabularies vs. one big hierarchical vocabulary with parent terms
Context: I'm developing a website (a directory of things) with a content type "product" that relies on an extensive list with actually two levels: say "productname" and "productvariation". In real life this could be "fruits" or "beer" for the first level "productname" and then "strawberrys", "apples", "peaches" or "stout", "wheat" or "lager" for the second level "productvariation". There won't be a third level as all variations will go on that second level even if they are a subcategory of one variation. It's important that the content type can hold unlimited values of "productnames" (first level) and subsequently unlimited values of "variations" from the selected "productnames".

I want easy editing for the people who will maintain this site. I'm thinking conditional field architecture: User selects one ore more products (radiobuttons or checkboxes)and then the appropriate (select) lists of variations appear for further selecting.

Right now I'm thinking the first level as different vocabs but I don't know if this is the right way?

I haven't found a way to display the vocabs as a list (like a term reference field) so I'm doubting my draft. Is the above a misconception and i should use just one vocabulary?

Thanks in advance!

# Answer
> 2 votes
In the general term you should think on your requisites for these three things, and the pros/cons of the options provided by Drupal core/contrib to accomplish them:

1. How to create and maintain the hierarchy of terms
2. How to pick terms from the hierarchy when creating/editing products
3. How to filter products with a criteria based on this hierarchy (views or programatically filtering)

The way you decide to go for the 1st point (one hierarchical vobcabulary or two related vocabularies) determines the options available to solve the other two points.

When using one hierarchical vocabulary, the most important thing IMO is to preserve the lineage: when classifying a product as strawberry, also classify it as a fruit. This is very helpful to cleanly address the 3rd point without frustration, neither with inelegant approaches. Drupal core doesn't provide a way to preserve the lineage when creating entities. There're several modules out there that ensures it. The most powerful, Hierarchical Select.

Also, editing the hierarchy of terms via the core interface is a bad UX when you go above a few dozens of terms. To improve this there're modules like Taxonomy Manager.

Lastly, eventually you may face scale problems if the vocabulary is huge.

OTOH, using two vocabularies brings other pros/cons.

On the pros side:

* Configuring different fields in each of the vocabularies. For example, in the first level vocabulary (usually called *family*) a boolean field indicating whether the product is *perishable*, and a image field in the second level vocabulary for a photo of the variation.
* Preserving the lineage is not an issue, since you are selecting values in two different field/widgets that you enforce to be required.

On the cons:

* You're on your own with two independent vocabularies/fields that needs to be dependant somehow. You may want to create entity reference fields from parent to child, or the other side. You also need a dependant selector widget, eventually you want this widget to work also in views exposed filters,...

The Reference field option limit is great for this setup. It is a bit hard to get how it works, and it has some issues (specially I remember problems with i18n) but it does it pretty nice.

In conclusion:

* None of both approaches works 100% out of the box
* In the one-vocab approach you want to solve the lineage problem
* Two vocabularies is more versatile
* Two vocabularies is harder to setup

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


# Question
Title: Votingapi REST server call internal server error - 'services exception: missing entity ID'
I am trying to post votes to 'fivestar' ratings on my D7 site, through my iOS app (xcode7, swift2). My iOS swift API to post a vote to the votingapi REST services post gives me a 200 status ok, and no errors. But my Drupal site/database does not register/save the vote. When I use the URL directed in Drupal services definitions I get status 500 (internal server error) and this log message (on 2 sites I'm testing on);

```
  ServicesException: Missing entity ID for vote tag in services_error() (line 366 of /home/example/public_html/example.com/sites/all/modules/services/includes/services.runtime.inc)

```

So I am wondering which is the correct URL and if I should use the URL without the node then how to fix this 'entity\_id' error, if that is the problem? U

Here is my code:

```
    // submit vote

    let voteEndpoint: String = "https://www.example.com/node/7291/ios1/votingapi/set_votes"
    let newVote = ["votes":["value":40, "uid":235, "vote_id":75000, "timestamp":146882901,  "vote_source":"70.36.223.173", "entity_id":7291, "entity_type":"node", "tag":"vote", "value_type":"percent"]]
    Alamofire.request(.POST, voteEndpoint, parameters: newVote, encoding: .JSON)
        .response { request, response, data, error in
            print(request)
            print (response)
            print (error)
    }

```

After repeating the URL as given above, the console returns:

```
 { status code: 200, headers {
    "Cache-Control" = "no-cache, must-revalidate";
    Connection = "Keep-Alive";
    "Content-Language" = en;
    "Content-Type" = "text/html; charset=utf-8";
    Date = "Tue, 19 Jul 2016 00:09:53 GMT";
    Expires = "Sun, 19 Nov 1978 05:00:00 GMT";
    "Keep-Alive" = "timeout=10, max=200";
    Link = "</node/7291>; rel=\"shortlink\",</Never-Return-to-Venice-chapter5>; rel=\"canonical\"";
    Server = Apache;
    "Set-Cookie" = "DRUPAL_UID=0; expires=Mon, 18-Jul-2016 00:09:53 GMT; Max-Age=-86401; path=/; domain=.example.com; secure, DRUPAL_UID=-1; expires=Thu, 11-Aug-2016 03:43:13 GMT; Max-Age=1999999; path=/; domain=.example.com; secure";
    "Transfer-Encoding" = Identity;
    "X-Content-Type-Options" = nosniff;
    "X-Frame-Options" = SAMEORIGIN;
    "X-Generator" = "Drupal 7 (http://drupal.org)";
    "X-Powered-By" = "PHP/5.6.9"; } }) nil

```
* The drupal system and voting modules are up to date
* I have cleared cache and run cron.
* I have tried testing it with a new services endpoint
* I have no status report errors reporting any problems with the voting modules.
* There are no error messages in the Drupal log
* The anonymous permissions are set to allow voting.
* voting is saving normally on direct votes on the drupal site.
* There is no authentication on the drupal services, and voting api is set.
* Developers have confirmed my swift code looks correct
* according to this drupalcontrib webpage information, my votingapi parameters are correct, yes? see drupalcontrib.org/api/drupal/contributions%21votingapi%21votingapi.module/class/VotingApi\_Vote/7
* my database does not mention 'votes' but for the array it does confirms these parameters I have used are the correct parameters.
* web surfing confirms these are correct values for the parameters, with the only mandatory parameters as 'value', 'uid', 'entity\_id', 'entity\_type'. I have tried using only those parameters, same result.

I have tried a multitude of variations, but all of them give status 200 but no vote in my drupal database. I tried rate module (and its custom tags instead of 'vote') but get the same result. I tried without .json at the URL. I tried other possible variations of entity\_type eg 'article' instead of 'node' etc. I tried without the node/xxxx in the URL. I tried without 'vote' (as per other modules), 'criteria' instead of 'votes'.

I am using the node ID for the "entity\_id". Is that correct?

Any ideas?

IS it something with this: \- Drupal services definitions lists: SET\_VOTES Set votes for an entity POST : https://www.example.com/ios1/votingapi/set\_votes

The rest service endpoint is ios1. When I include node/7291 in the URL (before ios1), hooray it returns status 200. BUT it doesn't register the vote in the database. When I use the URL (without the node) as per the Services Definitions, I get status 500 and the 'services exception: Missing Entity ID' error (above).

The site's services definitions -as per this screenshot- confirms the parameters as an 'array' for 'votes'. And an array for 'criteria' as not mandatory. Please see attached. \[\]\[1

# Answer
Solved: I added Basic Auth with a header of "Content-Type : application/json" and also an extra bracket around the array parameters.

This full code is passing votes successfully:

```
     // API request

    let user = "username"
    let password = "pass"
    let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Content-Type : application/json"]
    let voteEndpoint: String = "https://example.site/ios1/votingapi/set_votes.json"
    let newVote = ["votes":[["value":100,"uid":32,"entity_id":1,"entity_type":"node","tag":"vote","value_type":"percent"]]]
    Alamofire.request(.POST, voteEndpoint, parameters: newVote, encoding: .JSON)
         .response { request, response, data, error in
            debugPrint(response)
            print(request)
            print (response)
            print (error)
    }

}

```
> 0 votes

---
Tags: 7, users, services
---