# Question
Title: Displaying block only when user visits his own profile page
I want to display the block only when the current user visits own page. So in block visibility I use the following PHP:

```
global $user;
if ($user->uid == arg(1)) {;
return TRUE;
} else {;
return FALSE;
};
endif;

```

But that block returns on every page.What am I doing wrong?

# Answer
> 1 votes
If you are using the php code in the block visibility option than I guess the following should work:

```
<?php
global $user;
$user_id = $user->uid;
if (('user' === arg(0)) && ($user_id === arg(1))) {
  return TRUE;
} else {
  return FALSE;
}
?>

```

If your site is multi-lingual than may be you have to change the if condition as: `if (('user' === arg(1)) && ($user_id === arg(2)))`

# Answer
> 0 votes
The provided code is insufficient, as it does not check whether the user is editing their account (user/uid/edit), or simply viewing it (user/uid or user/uid/view).

```
<?php
$uid = $GLOBALS['user']->uid;
if ('user' == arg(0) && $uid == arg(1) && ('view' == arg(2) || NULL == arg(2))) {
  return TRUE;
}
return FALSE;
?>

```

The above code ensures that your block will ONLY ever be visible when the user account is being viewed (at /user/uid or /user/uid/view) by the user the account belongs to.

Personally, I would simply use Views to create a page, which uses a contextual filter that uses the currently logged-in user to display specific information about them.

---
Tags: blocks
---


# Question
Title: Content: tags contextual filter seems to only match the first tag
I have a contextual filter on the field `content: tags` set to "Match any value," but in practice, it appears that only nodes that match the first tag are displayed. For instance a node with the tags "blue, green" would show only other nodes tagged "blue."

# Answer
> 0 votes
The setting I was missing was under Advanced=\>Contextual Filters=\>Taxonomy term: Term ID=\>More and check "Allow Multiple Values"

# Answer
> 0 votes
It usually work better when you add a relationship to the view, where you relate the content to the taxonomy term. Then you unlock a whole new collection of fields and filters.

Choose to filter by taxonomy - name instead of content - tags.

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


# Question
Title: How to create a list of OG groups with no activity using Views?
How can I create a list of OG groups with no activity using Views. For example, the list of groups where users have not created/tagged any content within last 30 days.

**Note**: We do not have date field attached to Group content-type, the only date associated with groups is group post date.

# Answer
```
/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(&$view) {
  foreach ($view->result as $key => $row) {
    $node = node_load($row->nid);
    if ($node->changed > (time() - (30 * 24 * 60 * 60))) { // 30 days back in time();
    unset($view->result[$key]);
    }
  }
}

```
> 1 votes

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


# Question
Title: How to track field changes in custom (ECK) entities
I'm using Feeds to import an online spreadsheet into Drupal (ECK) entities. This goes okay but there doesn't seem to be a module (?) that allows to view the tracked changes in the entity fields. There is one module that is promising but doesn't yet support custom entities: "Track Field Changes"https://www.drupal.org/project/track\_field\_changes

So the question is: is there an alternative module or way to view changes of entities, especially the field changes?

I tried the diff module but that doesn't give an overview of entities that have changed?

# Answer
> 1 votes
You can try ECK Revision module. Also check related drupal.org issue: Support Revisions in ECK.

---
Tags: feeds, entities
---


title: Can't log in user with Rest service

text:
# Question
Title: Can't log in user with Rest service
i'm trying to build a Headless Drupal app with symfony, i'm stuck with login, i build a custom module for drupal 8 with four functions, (login,logout,register,login\_status):

```
<?php

/**
 * @file
 * Contains \Drupal\remoteuser\Controller\RemoteUserController
 */

 namespace Drupal\remoteuser\Controller;

 use Drupal\Core\Controller\ControllerBase;
 use Drupal\Core\Form\FormState;
 use Drupal\Core\Entity;
 use Drupal\user\Controller;
 use Symfony\Component\HttpFoundation\JsonResponse;

class RemoteUserController extends ControllerBase
{
  public function login() {
    $form_state = (new FormState())->setValues($_POST);
    \Drupal::formBuilder()->submitForm('\Drupal\user\Form\UserLoginForm', $form_state);

    // Check for errors from the from
    if ($errors = $form_state->getErrors()) {
      // Return errors to notify the client.
      return new JsonResponse( array( 'error' => $errors ) );
    }
    else {
      // Return new user session to client.
      $uid = \Drupal::service('user.auth')->authenticate($_POST['name'], $_POST['pass']);
      $session_manager = \Drupal::service('session_manager');
      $session_id = $session_manager->getId();
      return new JsonResponse( array( 'uid' => $uid, 'session_id' => $session_id ) );
    }
  }

  public function register() {
    // Validate the e-mail address first.
    if (!\Drupal::service('email.validator')->isValid($_POST['mail'])) {
      return new JsonResponse( array( 'error' => 'Invalid e-mail address' ) );
    }

    // Create password if it was not provided.
    $password = $_POST['pass'] ? $_POST['pass'] : user_password();

    /** @var \Drupal\user\Entity\User $user */
    $user = entity_create('user', array(
      'name' => $_POST['name'],
      'mail' => $_POST['mail'],
      'pass' => $password,
    ));

    // Validate the object.
    $errors = $user->validate();

    if ($errors->count() > 0) {
      // Return errors to notify the client.
      return new JsonResponse( array( 'error' => $errors->__toString() ) );
    } else {
      // Save new user
      $user->save();
      // Return new user credentials
      return new JsonResponse( array( 'user' => $user->toArray() ) );
    }
  }

  public function logout() {
    $result = user_logout();

    return new JsonResponse($result);
  }

  public function login_status() {
    $uid = \Drupal::currentUser()->id();

    $session_manager = \Drupal::service('session_manager');
    $session_id = $session_manager->getId();

    return new JsonResponse( array( 'uid' => $uid, 'session_id' => $session_id ) );
  }
}

```

all working great except for **login** !, it authenticate and returns successfully the user, but when i check with login\_status, it returns an anonymous user !!. but the magic is that when i test with Postman google chrome plugin, login\_status returns successfully the logged in user !!, maybe the cookies are not handled correctly in symfony !! i tried also with Drupal 7 Rest services, same problem, the user is not logged in !!

# Answer
> 2 votes
Finally, it works :D, I'll just put this answer here to help how still don't know how to login user via my custom Web Services API, i had to manage the cookies from the frontend, I use symfony, after sending a POST request to /{endpoint}/user/login, and receive the response that will look like this:

```
{
    "sessid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
    "session_name": "SESS948facaca231cedd9a2a526239dcb6dc",
    "token": "icfD3CNT4r4QAlEGiYmqzez0MVmsPbAowVR8HtfaD4Y",
    "user": {
        "uid": "1",
        "name": "admin",
        "mail": "contact@headless.com",
        "theme": "",
        "signature": "",
        "signature_format": null,
        "created": "1459037019",
        "access": "1459439836",
        "login": 1459440402,
        "status": "1",
        "timezone": "Europe/Paris",
        "language": "",
        "picture": "0",
        "init": "contact@headless.com",
        "data": false,
        "roles": {
            "2": "authenticated user"
        }
    }
}

```

i create a cookie with (any name) and the value will be "session\_name=sessid", don't forget the "=". and finally to see if the user is logged in, you need the token and the cookie that you created, send a POST request to {endpoint}/system/connect WITH this HEADERS:

```
X-CSRF-Token: token from the login response
Cookie: SESS948facaca231cedd9a2a526239dcb6dc=ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q (session_name=sessid)

```

and voila :D, you get a response like this:

```
{
    "sessid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
    "session_name": "SESS948facaca231cedd9a2a526239dcb6dc",
    "user": {
        "uid": "1",
        "name": "admin",
        "mail": "contact@headless.com",
        "theme": "",
        "signature": "",
        "signature_format": null,
        "created": "1459037019",
        "access": "1459440402",
        "login": "1459440402",
        "status": "1",
        "timezone": "Europe/Paris",
        "language": "",
        "picture": "0",
        "init": "contact@headless.com",
        "data": false,
        "sid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
        "ssid": "",
        "hostname": "127.0.0.1",
        "timestamp": "1459440402",
        "cache": "0",
        "session": "",
        "roles": {
            "2": "authenticated user"
        }
    }
}

```

i hope my answer help any one how is looking for how to login users via Drupal Services.

---
Tags: 8
---


# Question
Title: How do I manage core and module updates along with config management between environments?
I've set up a dev site, a test site, and a public site. Dev and Test are in two separate virtual machines (VLAD) and Public is on a shared Dreamhost account. I've successfully used the Configuration management tool to get all three of these environments in sync by installing it once, then copying the files (git) from one to the other environments, and exporting/importing the database information. Now it is time for me to update something like Drupal core from 8.0.3 to 8.0.4 and I am unsure exactly how that should happen with relation to getting that update on the other two environments. **So, the main question is: how should I migrate/deploy/manage the upgrade between environments taking into consideration the need for UUID and CMI to stay intact?**

Should I update one environment, lets say dev, using whatever chosen tool I have handy (like `drush up --security-only` or download the new version, and hit update.php in the browser, etc.) then copy those files from dev to test and re-export/import the database info? **Or**, should I update each of them individually? I suppose the thing I'm most worried about is will that break configuration management? Maybe I don't need to export/import database files and instead just export/import config changes after updating drupal or some contrib module into the dev site.

I've read what feels like 50 different posts about CMI and how to use it and how Drupal 8 makes some of this so much better and I totally agree about the information that actually gets managed by that tool but I can't seem to find information about how to deal with upgrading core and modules between these different environments. If I'm just not reading the right doc or blog post correctly and you can point me to one that is **great**. If you can answer directly here that is **great** too. And, maybe I'm just not "getting it" so please feel free to set me straight.

My question may be similar to the one posed here but it isn't exactly worded the same, so, again, I may just be missing the easy answer here.

# Answer
Yes, the referenced issue is related but I think this deserves a separate answer.

I agree this situation isn't fully satisfactory, but it's not too much of a problem.

In most environments, it won't be possibly to avoid manual configuration changes on production entirely. For example, contact forms are configuration (and not just a single file but 3 + 2 * number\_of\_fields) and users will likely create new ones without going through staging.

That basically means that you have to live with the situation that there can always be changes on production that are different from what happened on staging/dev. And that you have to treat the configuration on production as the master, unless you're deploying specific changes.

My process for deploying configuration changes usually looks like this:

1. Do the changes, commit them to a feature branch.
2. Export the configuration from production and commit it to whatever branch you use for that (for me, that's usually a branch called "production")
3. Merge your changes into that. Resolve conflicts if necessary.
4. Deploy the code to production.
5. Verify the configuration changes, make sure that ther are only known changes that know you prepared for deployment.
6. Import the configuration.

Module updates add the additional problem of update functions. If you have those, you need to run them between steps 4 and 5. Usually, those aren't a big problem unless they create new configuration with new UUID's. Then you have a problem if you want to import the same configuration entities from the staging config since those would have different UUID's and it would lead to deleting and re-creating them. You have to merge back the changed configuration from production before you can do that.

In general, I'd recommend to not mix module updates with feature/configuration deployments. Do module updates first, export the configuration again, then deploy again with new configuration.

Note that enabling new modules isn't affected by this, unless the module is installed by an update function. But if you deploy new modules through an updated core.extension module list, the config system supports that explicitly by taking the new configuration from your configuration export and not the module's clean default installation. So it's perfectly supported to enable a module on staging, customize its default config (not just simple configuration but also views and so on) and then deploy it to production.
> 2 votes

---
Tags: 8, updating, configuration
---


# Question
Title: How to restrict number of quizzes that somebody can take in a day
I am new to quiz module. I wanted to restrict the users, in a way, they can take only a particular number of quizzes in a day. For example a user with name 'A' can take only 'x' number of quizzes in a day, and after that if somebody tries, should end up with a warning message 'Try tomorrow again'.

Anybody has come up with such ideas?. If not how can I achieve the same.

# Answer
I have not used the quiz module myself but I think I would start with a custom module using HOOK\_form\_alter() to call a function that would parse the UID from quizzes where the published time is within the last 24 hrs. If you find more than 5 then you block access or redirect. This is just to get you started. I have not tested it.

```
function current_quizes(){
    //Get today's date.
    $today = getdate();

    //Get current time.
    $end_time = time();

    //Get the current user
    $current_user = $user->uid;

    //Calculate the date yesterday.
    $start_time = mktime(0, 0, 0,$today['mon'],($today['mday'] - 1), $today['year']);

    //You will have to tweak the DB query based on how the quiz module stores its information
    $query = db_select('node', 'n')
        ->fields('n')
        ->condition('status', 1) //Published.
        ->condition('created', array($start_time, $end_time), 'BETWEEN') //in the last 24hrs
        ->condition('uid', $user->uid) //This is our guy
        ->execute();

    $tests_taken = 0;
    foreach ($query as $value){
        ++$tests_taken; //Every entry is a test taken in the last 24hrs
    }

    return $tests_taken;  //Return total tests taken
}

```
> 0 votes

---
Tags: 7, quiz
---


# Question
Title: Date token to use user timezone instead of site timezone
Our site is having users from different timezones and we are sending event notification emails using rules. We need to specify the event date-time in addressee's timezone.

So, is there any way to specify the the timezone within/along with date-time token?

Or, should I introduce a custom token for this purpose?

# Answer
> 1 votes
You can try date token with custom date formatting

```
[entity:field-event-date:custom:m/d/y T]

```

replace `entity` with appropriate token (`node`, etc.), and insert the name of your date field.

Refer to PHP:date - Manual for custom date formats.

---
Tags: tokens, datetime
---


# Question
Title: How to collect and display visit statistics for a Views page?
I wonder if someone can point me in the right direction for the following:

I'd like to collect and display statistics for a Views page.

I wonder what's the best approach for collecting basic 'hit' statistics for a views page (essentially a visitor counter for that view). The view uses contextual filtering (i.e. nid) to render content. Ideally, each path (i.e. viewpath/12, where 12 is the nid) has separate statistics.

Any guidance is appreciated.

# Answer
Have a look at the Visitors module. Here are some reports you get from it:

> * View pages that have recently been visited.
> * View pages that have been hit frequently.
> * View pages count per month, day of month, day of week, hour.
> * ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

* Top pages (table with columns Title, Path and nr of Hits).
* Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor).

Checkout the above (source) links to get an idea of which data are available.

Extra reporting features can be enabled via these sub-modules:

* The **Visitors GeoIP** module, to also report about countries and cities.
* The **Visitors Browscap** module, providing statistics on visiting browsers.

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors\_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.
> 2 votes

---
Tags: views, nodes, google-analytics
---


# Question
Title: Is there a 'official' place to put PHP snippets?
If I wanted all PHP removed from the front end (meaning not in views, not in the body of blocks), but someplace hidden in the background, is there a 'official' recommendation for doing so?

Drupal's framework is PHP so I figured it would have some sort of standard for this type of thing, but it doesn't appear to be the case.

# Answer
I would quickly answer no to your question (and explain myself below).

The only thing that comes to my mind as a kind of answer is "place it in a hook".
But as you probably know, there are tons of these.
So, there is not one single "official" place, if I get your point right. Plus, using a hook means placing your PHP Snippets in files. Is that in agreement with your question? Or, is your question better phrased as "Is there a 'official' place ***in the configuration*** to put PHP snippets?"

Well, hope this explained the "no" answer some, if I am off, please do elaborate some more.

Cheers!

P.S.1: Sounds interesting, sounds like you have something specific in mind. :-)
P.S.2: It's worth mentioning that there are even some modules like the Computed Field that guide you (through naming conventions) to place your snippets inside specific functions. This is similar to the hook idea, but fantastically presented and suggested in the field's configuration. It's one of the reasons I am so very fond of the Computed Field
> 0 votes

# Answer
> If I wanted all PHP removed from the front end (meaning not in views, not in the body of blocks)

Then you would use template files. Create a template file (.tpl.php) for your view or for your block and put the php code there.

The template file goes in `/sites/all/themes/YourTheme/templates` folder.

### Example:

If when you edit your block the url is `admin/structure/block/manage/block/8/configure` which means the 8 is the block ID.

Then template file name is **block--block--8.tpl.php**

Copy the code in block.tpl.php file located in `/sites/all/themes/YourTheme/templates` and paste it into your block--block--8.tpl.php file. Then add your custom php code somewhere in there.

Remember to clear/flush the Drupal cache to see changes.

---

For View's you could create a template (.tpl.php) file OR you could use template.php

It really depends on the use case to select which method is the best way to go. I would need more details about what your view's php code does in order to give you a proper solution.

---

**PS:** It is good that you're asking this as using the **PHP Filter** module or Views PHP is considered bad practice. See What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc?
> 0 votes

---
Tags: 7, configuration
---


title: Search API: Custom relationship?

text:
# Question
Title: Search API: Custom relationship?
Q: Can I combine two (geofield) field instances from different relationships into one aggregated Search API field?

So far I tried search\_api\_combined, which seems ok, but does only support the default field types, but not geofield LatLong for proximity search.

I was thinking that I could somehow craft a custom relationship that, for a given (product) node fetches one of the two profiles, or one of the two field instance values.

I guess all I need to know really is where the relationships in Search API are coming from.

Use case details:

* Two profile2 profile types: Private person, merchant. Usually one person has only one such profile. In case of doubt, I would pick one and ignore the other.
* Both contain a field instance of "field\_coordinates" geofield.
* Both contain a postal address field that acts as a geocoding source for the geofield, but with different granularity (private person only specifies postal code, merchant specifies full address). (This is one of the reasons why I'm using profile2) (This is not central to the question, just to give a better idea about the problem space.)
* Search API and Facet API.
* Product nodes with authors.
* Profile2 geofield field\_coordinates should act as the location for products.
* Search index for products should combine the field\_coordinates from different profiles into one aggregated field.

# Answer
> 0 votes
Oh, this turned out to be easy. Use hook\_entity\_property\_info\_alter() to define a new property.

```
/**
 * Implements hook_entity_property_info_alter().
 *
 * @see profile2_entity_property_info_alter()
 */
function MYMODULE_entity_property_info_alter(&$info) {
  // Add related profiles to the user object.
  $properties = &$info['user']['properties'];
  $properties['MYMODULE_profile2'] = array(
    'type' => 'profile2',
    'label' => 'Profile 2 (MYMODULE)',
    'description' => 'The first profile2 profile that can be found on the user.',
    /* @see _MYMODULE_get_profile2() */
    'getter callback' => '_MYMODULE_get_profile2',
    # 'bundle' => $type_name
  );
}

/**
 * Entity property callback.
 *
 * @param object $account
 * @param array $options
 * @param string $name
 *
 * @return object|null
 *
 * @see profile2_user_get_properties()
 */
function _MYMODULE_get_profile2($account, array $options, $name) {
  $profiles = profile2_load_by_user($account, NULL);
  return reset($profiles) ?: NULL;
}

```

---
Tags: 7
---


# Question
Title: How do you change the URL alias of a contact form?
Sounds simple enough, right? I can't find it anywhere. My contact form's path remains:

```
/contact/contact_us

```

And I have no idea where to change this. I have checked under the form settings at:

```
/admin/structure/contact/manage/contact_us

```

Which leads me to believe that perhaps all contact forms are in the structure:

```
/contact/[FORM_SYSTEM_NAME]

```

Is that the case or is it possible to change it?

**UPDATE**

What I really want is a simple ALIAS field per contact form, so I can set the url alias myself?

# Answer
> 10 votes
I went under Configuration --\> URL Aliases, and added a new alias for /contact-us that points to /contact/contact\_us

I expected the result to be that anyone typing in /contact-us would end up at /contact/contact\_us, but instead the opposite is happening. Anyone typing in /contact/contact\_us is now redirected to /contact-us and the page is shown there.

This is a little different from how Drupal 7 works, but this is the answer I needed.

# Answer
> 2 votes
You can, in fact, change it. To do that you should use a route subscriber service class.

Such class will implement the alterRoutes method which will give you the ability to change the path of the contact page.

*I'll update with code examples when I'll be near my computer.*

# Answer
> 1 votes
Yes, that is the case. You can't *change* that.

That said, you can always add aliases and use whatever path you want as an alias for /contact/form-id. It's not available directly in the contact form (there's an issue open for that, though) but you have to manually add it from the alias overview page at `admin/config/search/path`.

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


# Question
Title: Not able to find login form anymore on Drupal
We are not able to find the login form anymore on Drupal. We can't find the form on site.com/user/login... We can't find it anywhere.

How can we login?

# Answer
Maybe a problem of clean urls?

Try site.com/?q=user
> 1 votes

# Answer
If the login form is not showing in `/user/login` then what you need to do is to switch back to the default (bartik) theme by modifying your database OR using Drush.

See this answer 3 simple steps to recover your site OR Unusable Theme: How to Reset Your Theme
> 0 votes

# Answer
I would start by clearing the menu cache.
> 0 votes

# Answer
I've given this advice before and it has actually helped a few people. Load /user and delete all css using inspect in the Browser. Sometimes css that works on one page removes a part of another page.
> 0 votes

---
Tags: forms, users
---


# Question
Title: How to use CiviCRM Entity for searches with Facet API
I am trying to create a faceted search on CiviCRM contacts. I have created an index using the Search API module and the Facet API module, but currently the CiviCRM contacts can only be indexed on their ids, not their names. Obviously, that ain't so useful for humans to read...

For example, config/search/search\_api/index/MYINDEXNAME/fields brings up the CiviCRM contacts as a possible field, but the default value is integer, not fulltext or string.

I was suggested CiviCRM Entity as a fix for this, but I can't quite work out how it could solve the problem -- would be very grateful for any pointers, or any other ideas!

# Answer
A wee bit of info here:

http://forum.civicrm.org/index.php?topic=32169.0

but seems like u'll need to dig around and help build it

lobo
> 0 votes

# Answer
I believe that CiviCRM Entity and Facet API can do this and it is well explained in this blog
> 0 votes

---
Tags: entities, search, civicrm
---


# Question
Title: How to add a "company name" as a user value for permissions and a data variable
I am creating a site that allows multiple different company's access to separate resources. Access to resources is dependent on the user's role and the company they are registered to.

Sample User Roles: Mechanic Scheduler Parts Distributor Driver Admin

Sample Company's: Joe's Auto Repair Car Repair USA Pro Tire & Oil

Each user has access to only his company's data and the data that is associated with the permissions attached to his role.

How can this be done? Am I going to need to code custom modules?

# Answer
> 0 votes
This article can be helpful for you: https://www.drupal.org/node/200631, and you can try Taxonomy Access Control module to implement it.
Or another way you can try Organic groups \- its more powerful.

---
Tags: users, hooks
---


# Question
Title: How to programmatically publish/unpublished node using flag link and without using Rules?
I have implemented the functionality on flag link click the content are unpublished and click on unflagging the content are published. By using the Rules module.

But this time I want to implement same functionality **without using rules** module and instead **using custom coding**.

Any suggestions?

# Answer
Any module may react to a piece of content being flagged by implementing `hook_flag()`. Here is the relevant do so:

```
mymodule_flag($action, $flag, $content_id, $account) {
  if ($action == 'flag') { // Or $action == 'unflag'.
    // Do something in response to the flagging.
  }

  if ($flag->name == 'yourflagname') {
    //Your custom code to unpublish/publish the content goes here.
  }

}

```

Source: "Responding to a flagging", located within the Flag's community documentation.
> 2 votes

---
Tags: flags
---


# Question
Title: How do I edit the template files for GLOBAL PHP?
I have a global php field in a view and it has a output field. However, I want to add / edit the template file instead which looks like this:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php print $output; ?>

```

However, when I put anything here, like for example: `echo "hello world";` nothing gets displayed.

If I put this php code in the output field on the view, it works just fine, but I am tasked with removing php from fields and putting them in either modules or template files so they do not risk exposure.

How come my template file will not display whatever php code I insert, but it will on the field itself? I'm confused.

# Answer
> 2 votes
1) Remove Global PHP field from the view

2) Add a new field of type "Global: Custom text"

3) Click on Theme: Information. You will be able to see the suggestion for template file

4)Create the template file with the required name.

5)Invoke the function which was being invoked from your Global: PHP field.

# Answer
> 0 votes
This article can be helpful for you: How to properly use PHP on Drupal views fields.

---
Tags: 7, theming
---


# Question
Title: How can i display child terms under parent terms and assigned articles using entity field query?
Hi i have one content type with two vocabulary term references one is called **category** and terms is **A,B,C** like the 2nd one **resources** it contains parent with child terms like below hierarchy

```
Resource 1

    Subsection 1
    Subsection 2
    Subsection 3
    Subsection 4

Resource 2
Resource 3
Resource 4

```

so i want to display articles based on first taxonomy **category** then 2nd taxonomy **resources** related items using entity field query below hierarchy

```
Resource 1

    Subsection 1

        Article 1
        Article 2

    Subsection 2
    Subsection 3
    Subsection 4

Resource 2
Resource 3
Resource 4

```

below is my code for display only 1st taxonomy based articles fetching but i need to display both cases please help.

```
        <?php
        $vocab = taxonomy_vocabulary_machine_name_load('resource_category');
        $trees = taxonomy_get_tree($vocab->vid);
        $array_tree = array();
        $array_tree1 = array();
        foreach($trees as $tree)
        {
            if($tree->depth == 0)
            array_push($array_tree,$tree->tid);
        }
        $i = 0;

        foreach($trees as $tree)
        {
            foreach($tree->parents as $parent)
            {
                if($parent != 0)
                {
                    $array_tree1[$parent][$i]=$tree->tid;
                    $i++;

                }
                //~ if(array_search($tree->tid,$array_tree))
                //~ array_push($array_tree1,$tree->tid);
            }

        }
?>
<ul>
<?php
foreach($trees as $tree)
{
    if($tree->depth == 0) {
    echo '<li>'.$tree->name;
    if(count($array_tree1[$tree->tid]))
    echo '<ul>';
            foreach($array_tree1[$tree->tid] as $sub)
            {
                echo '<li>'.$sub.'</li>';
                $query_resources = new EntityFieldQuery();
                $query_resources->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'resouces')
                        ->propertyCondition('status', NODE_PUBLISHED)
                        ->fieldCondition('field_resource_category', 'tid', '21')
                        ->fieldCondition('field_resources_subcategory');
                $result_resources = $query_resources->execute();
                if (isset($result_resources['node'])) {
                    $news_items_resources = array_keys($result_resources['node']);
                    $news_items_res = entity_load('node', $news_items_resources);
                        //echo '<pre>';print_r($news_items_res); echo '</pre>';
                } else {
                    echo '<p><strong>No Resources</strong></p>';
                }
                    }
            echo '</ul>';
            echo '</li>';
        }
}

?>

```

# Answer
> 1 votes
Term relationships aren't kept in a table that the entity API knows about, so you can't use an EFQ to query them.

`taxonomy_get_tree()` exists for exactly this purpose:

> Create a hierarchical representation of a vocabulary.

e.g.

```
$vocab = taxonomy_vocabulary_machine_name_load('foo_vocab');
$tree = taxonomy_get_tree($vocab->vid);

```

You can optionally provide a `$parent_id` as a 2nd argument, to force the root of the tree to a specific term.

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


# Question
Title: How to create a block view containing data from another Drupal site?
I'm new to Drupal. I'm working on existing Drupal Website. This is a multi-site with single Drupal Setup.

There is a side-bar on the website that contains a view for News of website. I want to create another view like "News" and put it to below the "News" view inside the same block.

The new view will contain events instead of news and those events will come other websites (other websites is the sites from multi-sites, I have total 3 websites in multi-site setup).

Please help me to do this. Please let me know if I need to share more details.

# Answer
I am assuming that the view that is already in use is of type block.

You can clone the Block using the views admin UI.

1)Go to Structure -\> Views

2)Click on the Edit link corresponding to your view

3)Click on the block you are interested in copying and select the option "Clone Block" from the dropdown.

4)A copy of the block gets created. Update the title of the new block , make the necessary changes to the filters etc and save.

oops!Missed out the important piece "

> The view should display the events which are currently available in a different site

"

From what I understand the multi-site setup is achieved using the Domain Access module. So the drupal instance and the DB are common for all the sites.

In your case you need to make the events content available in the domain where you are creating the view. To do this 1) Go to Structure -\> Content Types

2) Click on the edit link corresponding to the Events content type

3) Click on "Domain Access Settings" at the bottom

4) Select the Domain where the events view is going to be added and save.

5) This domain access setting gets applied to all the new events which get added after the change.

6) The existing events might have to be manually updated to make them accessible in the different domain. Go to the edit page of each specific event and update the Domain Access options accordingly.
> 3 votes

# Answer
> The new view will contain events instead of news and those events will come other websites (other websites is the sites from multi-\>sites, I have total 3 websites in multi-site setup).

I could be wrong, but I don't think multi-site with single Drupal Setup lets you share content from 1 site to another.

From what I've heard is that you need to use

### Domain Access

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The **module allows you to share** users, **content**, and configurations across a group of sites

Intro Video
> 1 votes

# Answer
To my knowledge there is no solution to make this works with (only) Views. But if you're willing to use the Forena module, you could make this work as detailed below ...

Forena has an integration with the BEAN module, as explained in its documentation about Bean Integration. So you can create your **News** block via this integration.

To actually build such block, you'll basically have to do 2 things:

1. Write your appropriate SQL statement (to create what is called the "data block", stored in an SQL file in your file system). If you're an SQL expert you just write the SQL, as an alternative you can use the **WYSIWYG Query Builder** (think of using PhpMyAdmin within a Drupal admin interface).
2. Create a "report" which will actually display the query results of your data block and format it to fit your needs. The specifications (design) of this report is stored in what is called a .FRX file, which is basically a file in XHTML format. You can use the **WYSIWYG Report Writer** to have Forena guide you in the creation of this report (which will save it as a .FRX file). More experienced Forena users will more and more just create/modify the .FRX files directly.

What is above is a high level overview of how to build such **News** block with Forena. What is left is to do something which is pretty similar for creating your **Events** block. The clue for this part here is that when you're defining a data block, you do so by referring to a "database connection". So to build your News block, the approach is similar, but it only points to the data of your other site(s). In this case it's pretty easy (its also a Drupal database), but it could even have been an Oracle, MS SQL, PostgreSQL, etc database also.

For (way) more details, head over to the Forena Documentation included with the module (or its equivalent in the demo site). Or have a look at various questions around here tagged with ... and add your own questions if needed (using this tag).

**Disclosure**: I'm a (co-)maintainer of Forena.
> 1 votes

---
Tags: 7, views, blocks
---


# Question
Title: Simplenews adds newsletters title at the top of the newsletter
I have a Drupal-7 site and a testing one and a weird thing happens. When I send a newsletter from my testing site everything is ok, but when I send from the actual site, the title of the newsletter is added at the top of the newsletter. So the newsletter appears like this:
**Title**
Title
images , which is what I want to only appear.

Another weird thing that happens, is that the title appears only at some emails like outlook, but not on gmail or hotmail.

My question is, why do you think that this happens?Do I have to check my administrator options, or is this a code issue, like at simplenews.module file?
Thank you in advance!

# Answer
Find `simplenews-newsletter-body.tpl.php` in `modules/simplenews/theme` folder. Copy it to your current theme's folder and open/edit it. You'll see that it has a `$title` variable printed at the top. Comment it out and clear cache to make Drupal see your template change. Test and see the title gone.

```
REMOVE OR COMMENT THIS LINE =>  <h2><?php print $title; ?></h2>
<?php print render($build); ?>

```
> 3 votes

---
Tags: 7, emails
---


# Question
Title: Can trusted host settings use an IP address?
I'm working with a test site installed on a server on my network. Since it's only a sandbox, it has no domain name. Drupal being installed in a sub-directory (there are several sandboxes), I access it through an address like this: http://10.156.222.145/d8

However, when I put this in the trusted host patterns, like so:

```
$settings['trusted_host_patterns'] = array(
    '^10\.156\.222\.145\/d8$',
    '^localhost$'
  );

```

I get the error message: "The provided host name is not valid for this server."

Question: is it even possible to configure these settings with an IP address, and if so how?

# Answer
Yes using an IP is fine, you just need to make sure you're using a valid host name (I.e. one without the path appended):

```
^10\.156\.222\.145$

```
> 1 votes

---
Tags: configuration
---


title: Create cookie on login

text:
# Question
Title: Create cookie on login
What is the latest and best way to set a cookie upon login? What I mean is: if a user succesfully logins, then a session cookie **user-is-logged-in = 1** is set. When the user logs out, this is removed.

I see this https://www.drupal.org/project/logincookie but its very old and doesn't look supported.. I see this but https://www.drupal.org/node/2160739 but it starts with a requirement with Varnish which I don't have..

I am using Drupal version 7.43.

As you know session cookies set by Drupal don't do the trick, as anonymous users are also set a cookie and from a browser's perspective, they are not differentiable.

Thanks a lot for your help!

# Answer
> 5 votes
You could just write the code yourself in a custom module. What you want is pretty simple.

```
/**
 * Implements hook_user_login().
 */
function HOOK_user_login(&$edit, $account) {
  setcookie('user-is-logged-in', '1', 0, '/');
}

/**
 * Implements hook_user_logout().
 */
function HOOK_user_logout($account) {
  // Set cookie in the past and then remove it.
  setcookie('user-is-logged-in', '', REQUEST_TIME - 3600, '/');
  unset($_COOKIE['user-is-logged-in']);
}

```

---
Tags: cookies
---


# Question
Title: D7 - Ckeditor buttons get messed up when moving a site from one server to other
I just moved a D7 site from one server to another and the Ckeditor buttons get messed up. Look my capture. How can I fix this?

I use the Adminimal Theme but it is not the problem. If I switch to Bartik the problem persist.

I already cleared caches and run Cron several times.

# Answer
> 0 votes
Have you checked Css settings on Ckeditor profile page?

---
Tags: 7, wysiwyg
---


title: Error executing PHPUnit

text:
# Question
Title: Error executing PHPUnit
I was trying to write PHPUnit test in D8, but am blocked due to a weird issue which I am not able to track.

The module for which I am writing the test is at https://github.com/ajitdev/phpunit\_d8

I have created a basic class `Math` with some functions https://github.com/ajitdev/phpunit\_d8/blob/master/src/Math.php

```
<?php
namespace Drupal\phpunit_d8;
class Math {
  public function addNum($a, $b, $c) {
    return $a + $b + $c;
  }
  public function substract($a, $b) {
    return $a - $b;
  }
  public function divide($a, $b) {
    return $a / $b;
  }
}

```

And the test in `tests/src/Unit` directory https://github.com/ajitdev/phpunit\_d8/blob/master/tests/src/Unit/MathTest.php

```
<?php
/**
 * @file
 * Contains Drupal\Tests\phpunit_d8\Unit\MathTest
 */
namespace Drupal\Tests\phpunit_d8\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\phpunit_d8\Math;
/**
 * Class MathTest
 * @package Drupal\Tests\phpunit_d8\Unit
 *
 * @group math
 */
class MathTest extends UnitTestCase {
  public function addNumTest() {
    $math = new Math();
    $this->assertEquals($math->addNum(1,2,3), 6);
  }
}

```

The test shows up on `/admin/config/development/testing`, but throws the following exception:

```
Uncaught PHP Exception Drupal\Core\Database\IntegrityConstraintViolationException: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'file' cannot be null: INSERT INTO {simpletest} (test_id, test_class, status, message, message_group, function, line, file) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array
(
    [:db_insert_placeholder_0] => 14
    [:db_insert_placeholder_1] => Drupal\Tests\phpunit_d8\Unit\MathTest
    [:db_insert_placeholder_2] => fail
    [:db_insert_placeholder_3] =>
    [:db_insert_placeholder_4] => Other
    [:db_insert_placeholder_5] => Drupal\Tests\phpunit_d8\Unit\MathTest->Warning()
    [:db_insert_placeholder_6] => 0
    [:db_insert_placeholder_7] =>
)
" at /Applications/MAMP/htdocs/d8/core/lib/Drupal/Core/Database/Connection.php line 673

```

The issue is empty value for the `file` value. I am not able to trace down the issue. Any pointers would be really helpful.

# Answer
I was able to resolve the issue. You just have to prefix your test with `test_`. Seriously! No kidding!

My test looks like the following:

```
<?php
/**
 * @file
 * Contains Drupal\Tests\phpunit_d8\Unit\MathTest
 */

namespace Drupal\Tests\phpunit_d8\Unit;

use Drupal\Tests\UnitTestCase;
use Drupal\phpunit_d8\Math;

/**
 * Class MathTest
 * @package Drupal\Tests\phpunit_d8\Unit
 *
 * @group math
 */
class MathTest extends UnitTestCase {
  /**
   * Very simple test to MathTest::addNum().
   */
  public function testAddNum() {
    $math = new Math();
    $this->assertEquals($math->addNum(1,2,3), 6);
  }
}

```

Also, pushed at https://github.com/ajitdev/phpunit\_d8
> 1 votes

---
Tags: 8, testing
---


# Question
Title: How to prevent CKEditor trim plain text in source view
I'm using Drupal 8,

In source view when I paste some plain text like this:

```
Hello sir.
<br />
Hello  sir.

```

And submit node form, without toggling back to rich-text mode, text above is removed.

If I toggle back in rich-text mode before submitting, `CKEditor` automatically wraps my text in `p` tag, like this:

```
<p>Hello sir.<br />
Hello sir.<br />
Hello sir.<br />
Hello sir.</p>

```

So is it possible to make `CKEditor` wrap plain text in p without toggling back to rich-text view?

I have tried several things and failed in all of them, I have written custom `CKEditor` plugin which listens to submit button click and execute this `editor.execCommand( 'source' );` but it isn't working, somehow data is submitted before I switch to rich-text mode.

Is there any solution to this?

# Answer
CKEditor distinguishes *Output formatting* from *Source Code formatting*.

You're essentially wanting to do output formatting inside the source code formatting. It seems this is currently not possible.

From the documentation:

> **Configuring Source Code Format**
>
> At the moment the only aspect of the source code view that you can configure is the tab-size CSS property of the source editing area. Use the CKEDITOR.config.sourceAreaTabSize option to set the width of the tab character. Enter an integer to denote the number of spaces that the tab will contain.
>
> http://docs.ckeditor.com/#!/guide/dev\_sourcearea

You might play with using the popup source editor instead of the inline editor, I don't know if this would give you any more possibilities to plug into and alter the HTML in source-editing mode or not.
> 2 votes

---
Tags: 8, wysiwyg
---


# Question
Title: Views to use relative paths for image fields
How can we tell views to use relative paths for dispalying images using image fields. I have created a views slideshow which is displaying images using absolute url which is causing the images to reload on each page load.

facing the same issue in other type of views displays like grid and unformated etc...

# Answer
Add your image to the view (mine is called Image2)

Create a theme file for your image field, see screenshot. (mine is called views-view-field--relative-url-example--page--field-image2.tpl.php and it's bolded). Pick the last one for the most granular themeing possible.

(full size here)

After you have added the theme file to your theme templates (/sites/all/themes/THEME/templates or similar), hit the "Rescan template files" button. Your field template should be bolded now.

Add the following code to your theme file, I removed the comments but you can leave them in if you like:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php

    $url  = file_create_url($row->field_field_image2[0]["raw"]["uri"]);
    $url  = parse_url($url);
    $path = $url['path'];

    print $path;
?>

```

I only printed the path to demonstrate it works so you will need to add the image tag, etc.

Here is my output:

You may need to clear the cache and be sure to **save your view** after you update the theme file.
> 0 votes

# Answer
You can use image\_url\_formatter module ,it add url formatter in image field formatter than you can use it in content dispaly or field display in views.
> 0 votes

# Answer
This did not work for me, but stripping the domain from $output in my view template did:

```
$output = preg_replace('@http(s)?://www.example.com@', '', $output);
print $output;

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: Display of View (using grid) is unevenly distributed
Note: as a neophyte user, I'm not allowed multiple links or images. It has been suggested that I edit the hyperlinks so they're not quite right. Hopefully you can sort out what's going on.

Here is my view with taxonomy terms in columns, but you see that the columns are a bit wonky and not evenly distributed.

These are the the grid settings

And this is the page h ttp://imgur.com/puH2v1M

Thanks.

# Answer
My guess (I cannot be sure without seeing the HTML and CSS) is that the grid display uses HTML tables to create the grid. Because this looks exactly like what HTML tables do: they adjust their column width to the content in it. For instance, "General Fiction" is longer than "Genre" so the first table column is wider than the second. Because your view is grouped, every group would render a separate table, so that's why the columns cannot align.

Assuming that tables are indeed the cause, the solution would be to add custom CSS setting the width of `<td>` elements in this view to `33.3%`. (How you can do that, depends on your theme setup and is beyond the scope of this answer.)
> 1 votes

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


# Question
Title: Checking for changed fields - Identifying an empty array & Field Type
This is probably a simple question, but I am not finding it right away. I have a mostly working function to check for changed fields in a form. Here is the snippet checking for change:

```
// Check the number of values for each field, or if they are populated at all.
$old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
$new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

```

The problem I am a having is when I submit the form, empty text fields always respond as changed. The $old\_field\_count is not set, so comes up as 0. The $new\_field\_count is 1, because for some reason it is an empty array.

```
old count 0
new count 1 ... (Array, 1 element)
    0 (Array, 1 element)
        value (String, 0 characters )

```

There has to be an easy way to say "If ($new\_field\_count = "An empty Array") {$new\_field\_count = 0;}"

Edit: I found my answer in part. I tried `If (empty($new_field_count[0])) {$new_field_count = 0;}` but that just breaks any empty field that isn't a text field. So now I am thinking I have to additionally identify if it is a text field.

# Answer
Thanks, I've got it!

```
// Check the number of values for each field, or if they are populated at all.
$old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
$new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

If (empty($new_field[LANGUAGE_NONE][0]['value'] && ($field_info[type] == 'text' || $field_info[type] == 'text_long')) {
    $new_field_count = 0;
}

if ($old_field_count != $new_field_count) {
  // The two versions have a different number of values. Something has changed.
  $fields_changed[] = $field_name;
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Correct way to render an custom entity and its custom field?
In my module, I have a custom entity `LocationEntity` and it uses a custom field type `CoordinateItem` which has 2 sub fields `X`, `Y`.

So what is the correct way of Drupal 8 to:

1) Render this `LocationEntity` in a twig template?

* What I'm doing is just send the entity to twig template `'#loc1'` and manually render its each field value using getter method `{{ loc1.getName() }}`. It works but I'm sure this is not the correct way to do.

2) If question 1 has another correct way then how to have more than one templates for rendering the entity?

* For example, one simple layout with less fields and one detail layout with all fields.

3) In the entity, I defined to use the custom field `CoordinateItem`. But now what to do with its getter and setter, because it's not a single sub field inside?

* Getter if `$this->get('coord')` -\> a `FieldItemList` object.
* Getter if `$this->get('coord')->value` -\> `null`.
* Setter? What type is the parameter?

4) I wrote a formatter for `CoordinateItem` to show its sub fields. But again I don't know how to use this formatter to render this custom field in the main (entity) template?

* Maybe this is related to question 1 and 2?

# Answer
### View Builder

* 1. Set the `view_builder` in ContentEntityType annotation to EntityViewBuilder to inherit some default behavior (or write your own).
* 2. Set your `canonical` router to something like what `content_entity_example` does in the examples module.
        + Berdir suggests using DefaultHtmlRouteProvider though that class is marked as `@internal` so it may not be stable to use long term.

content\_entity\_example.routing.yml

```
entity.content_entity_example_contact.canonical:
  path: '/content_entity_example_contact/{content_entity_example_contact}'
  defaults:
    _entity_view: 'content_entity_example_contact'
    _title: 'Contact Content'
  requirements:
    _entity_access: 'content_entity_example_contact.view'

```
* 3. Change your entity theme to something like what node module does, and have it display as a render element.
* 4. Use your entity or bundle's field display page to change what field formatters a given field will use.
* 5. Then you can print out `{{ elements }}` in the template for it to go through the entire render array for a given view mode. Again, you can follow something similar to node module.
> 3 votes

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


# Question
Title: What is the Drupal 7 version of FILE_STATUS_TEMPORARY?
My use case is that I want to set an uploaded file as `FILE_STATUS_PERMANENT` until I know it has been processed correctly by my custom module. Once that is done, I'm happy for Drupal to delete it. There used to be a `FILE_STATUS_TEMPORARY` in D6 but no more. What should I use?

# Answer
That is strange, as `FILE_STATUS_PERMANENT` still does exist indeed. But the value of `FILE_STATUS_TEMPORARY` used to be `0`. So I suppose you can use anything that evaluates to zero: `FALSE`, `NULL`, `0`. Personally I have always used `0`.

But why set your file back to temporary to have it deleted by cron, why not just delete the file directly after processing? You can use file\_delete() to do that.
> 0 votes

---
Tags: files
---


# Question
Title: Get all enabled viewmodes of a entity/bundle
I need to get all possible viewmodes of a specific entity/bundle in D8. Currently I have this:

```
$viewmodes = \Drupal::service('entity_display.repository')->getViewModes($entity_type);

```

This shows all viewmodes on an entity, it doesn't filter on bundle. Also, the default viewmode is never included here.

Anyone knows a better way?

Cheers, Tom

# Answer
> 3 votes
What @googletorp said is correct. But there is a concept of "enabled" view modes, just not like you're apparently expecting.

Enabled view modes are view *displays*. Enabling a view mode for a given bundle creates a view display which then stores the formatter configuration.

Same for form modes and form displays.

And I think \Drupal\Core\Entity\EntityDisplayRepository::getViewModeOptionsByBundle() will kind of give you what you're looking for. The view modes for which the given bundle has a view display.

# Answer
> 1 votes
Your question is wrong :)

The thing with entity view modes is that they are created for a specific entity type, and will work on all bundles for that entity type.

A good example of this, is that all node types have the same view modes possible, you can select which ones you want to customize, but all of them will be available on all node types, if one isn't customized, the default is used instead.

---
Tags: 8
---


# Question
Title: Solve "Cron run failed" without Watchdog
Some years ago i wanted to turn off **watchdog** because it's memory and db consumption, but today i need info about why my **cron** isn't running because need to use *Search* module from now?

Trying to *run cron manually* (*admin/reports/status/run-cron*) return

> *Cron run failed.*

calling */cron.php* and running from server's command line has no return,

**How can i debug this?**

or

**There is any other way to turn on logging?**

> admin/settings/logging/dblog

has no return

```
SELECT * FROM `watchdog`

```

MySQL returned an empty result set

```
function watchdog()

```

still there in *bootstrap.inc*

*settings.php* and *.htaccess* free from any relevant *"error", "watch", "dog", "bdlog", "repor"* keywords (have no *php.ini*)

> /modules/dblog/dblog.module

still untouched. XML sitemap and *Search* is disabled

No *logging*, no *cron*, i am puzzled. Thanks for any help.

# Answer
> 2 votes
To enable the recording of the `watchdog()` messages, you just need to enable the *Database logging* module (short name: dblog). Once you enable it, on admin/reports/dblog you will start reading the recent log entries.

As for the possible error that could return cron, they are the following ones:

* Cron has been running for more than an hour and is most likely stuck
* Cron is already running and you try to re-run it

This is evident from Drupal code. The function that is executed when you go to admin/reports/status/run-cron is `system_cron_run()`, which returns the error you are seeing when `drupal_cron_run()` doesn't return `TRUE`. This is that function code.

```
  // Try to allocate enough time to run all the hook_cron implementations.
  if (function_exists('set_time_limit')) {
    @set_time_limit(240);
  }

  // Fetch the cron semaphore
  $semaphore = variable_get('cron_semaphore', FALSE);

  if ($semaphore) {
    if (time() - $semaphore > 3600) {
      // Either cron has been running for more than an hour or the semaphore
      // was not reset due to a database error.
      watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);

      // Release cron semaphore
      variable_del('cron_semaphore');
    }
    else {
      // Cron is still running normally.
      watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
    }
  }
  else {
    // Register shutdown callback
    register_shutdown_function('drupal_cron_cleanup');

    // Lock cron semaphore
    variable_set('cron_semaphore', time());

    // Iterate through the modules calling their cron handlers (if any):
    module_invoke_all('cron');

    // Record cron time
    variable_set('cron_last', time());
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);

    // Release cron semaphore
    variable_del('cron_semaphore');

    // Return TRUE so other functions can check if it did run successfully
    return TRUE;
  }

```

As for why Drupal thinks cron is still running, that happens when an error in the code (generally one of the `hook_cron()` implementations) doesn't permit `drupal_cron_run()` to execute the following line:

```
    // Release cron semaphore
    variable_del('cron_semaphore');

```

This means that to debug why cron doesn't work properly, you need to check any `hook_cron()` implementation, and see what is wrong with them. The problem could also be an implementation of `hook_node_view()` which is wrongly calling `drupal_goto()`.

# Answer
> 1 votes
If you have Drush available on the site, you can run this from the document root for that Drupal site:

```
drush cron

```

It should output errors so you can further troubleshoot. Also, if you have drush, you can enable dblog like so:

```
drush en -y dblog

```

# Answer
> 1 votes
Enabling the `Database logging` was the solution to enable **watchdog** (thank you @kiamlaluno), then this is the message after running cron:

> Message Attempting to re-run cron while it is already running.

Manually deleting `cron_semaphore` cause

> Cron ran successfully

but with *Search* module enabled cause

> Internal Server Error - 500

Then just changing this in *search.module* resolved the problem:

```
 function search_cron() {
  // Update word index
--  foreach (module_list() as $module) {
++  foreach (module_list(true, true, false) as $module) {

```

---
Tags: 6, cron, debugging, log-messages
---


# Question
Title: Adding a view desktop link to mobile site
I am using X-AH-Mobile-Redirect in the settings.php file to redirect visitors to the mobile site. I need to add a link so that visitors can switch to the desktop site.

Here is a snippet of the redirect code:

```
    if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
  switch ($_ENV['AH_SITE_ENVIRONMENT']) {
case 'dev':
   header('X-AH-Mobile-Redirect: http://m.mysite.com');
  break;
  }
};

```

# Answer
> 0 votes
I don't know about X-AH-Mobile-Redirect, but I did this a while ago by creating a link like http://example.com/?device=desktop and on page load I would check for $\_GET\['device'\] and for a cookie

Then I could just check

```
if (isset($_GET['device']) && $_GET['device'] == 'desktop') {
    setcookie('mycookie', 'true', strtotime('+365 days'));
    $mobile_browser = 0; //This forces site into desktop mode
}

```

Then on desktop version you just go the other way around with a http://example.com/?device=mobile

```
if (isset($_GET['device']) && $_GET['device'] == 'mobile') {
    setcookie('mycookie', null, -1); //Unset cookie
}

```

Of course you have to add whatever you need to force your mobile detector to go into mobile/desktop version, but it's pretty much it, on page loads check for the cookie and for the query strings and act accordingly.

---
Tags: redirection, mobile-tools
---


# Question
Title: How can I create a D7 View that groups and aggregates a "Rendered Node" field by date, grouping multiple instances for each grouped date?
I'm creating an event calendar and have run into this challenge. Say I have these events:

```
Concert A:
1/5/2016
1/6/2016
1/8/2016

Concert B:
1/6/2016
1/7/2016
1/8/2016

```

I want my view to display like this:

```
1/5/2016
Concert A

1/6/2016
Concert A
Concert B

1/7/2016
Concert B

1/8/2016
Concert A
Concert B

```

Right now I have a view which only shows the first instance of an event by date, and groups/aggregates distinct instances by date. Using the above data, this is my view now:

```
1/5/2016
Concert A

1/6/2016
Concert B

```

I'm currently grouping by a Date field which is set not to display. A second "Rendered Node" field displays the node using a view mode. This is driving me nuts. Anyone pull this off before?

# Answer
> 1 votes
You don't need the aggregation settings to get the result you want. Instead, I think you want the "Grouping field" option under the settings of "format".

Here is the export of a full View that I think yields the results you want:

```
$view = new view();
$view->name = 'date_group_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'date_group_test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'field_date',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
  'show_remaining_days' => 0,
);
$handler->display->display_options['fields']['field_date']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_date']['delta_offset'] = '0';
/* Sort criterion: Content: date (field_date) */
$handler->display->display_options['sorts']['field_date_value']['id'] = 'field_date_value';
$handler->display->display_options['sorts']['field_date_value']['table'] = 'field_data_field_date';
$handler->display->display_options['sorts']['field_date_value']['field'] = 'field_date_value';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

```

And a screenshot of the rendered View:

---
Tags: views
---


# Question
Title: How do I set the language code for rendering in entity_view()?
I'm trying to render entities using a Search API callback with entity\_view().

I want to register entities of type **user** in the **full** view mode as if viewed from the Japanese language. Here is my code:

```
// Explicitly set language to Japanese.
$render = entity_view('user', array(entity_id($type, $item) => $item), 'full', 'ja');

```

However, the output is still in English.

When I visit a user page rendered using the **full** view mode with a Japanese language user account, the page is displayed correctly.

So what am I doing wrong?

# Answer
> 0 votes
I'd recommend looking inside of user\_view() https://api.drupal.org/api/drupal/modules!user!user.module/function/user\_view/7

That function should be called by entity\_view() and it contains a drupal\_alter() call. Print out the $build variable that goes into drupal\_alter(). Is it using Japanese? Also print it out after the drupal\_alter(). Is $build now back to English? If so, some other module is altering the display.

---
Tags: 7, i18n-l10n, entities
---


# Question
Title: Suggestions for creating a more complex tiered content type
I need to create a content type where users will be able to create a tiered structure. This will be generated into a PDF and displayed using the Drupal templating system as well. I will need some sort of multi-valued field so that the user can add as many items as they like. I need the content structure to look like this:

* Content Title
* Custom Category Title

+ Custom item
    + Custom item Subheading
        - Custom subitem 1
        - Custom subitem 2
* Another Custom item

etc...

I'm considering Multifield (We've used field collection before and had issues with translation)

Or possibly a Custom Field type

If I used multifield, one option might be to have the user specify these things for each item ( Is it a subitem parent?, Is it a subitem?, If it is, what is it's parent?)

This is Drupal 7 and we'll be using Entity translation to handle translating this content type for all of our domains.

# Answer
I would definitely suggest using paragraphs, it's a killer module for multi-valued, arbitrary ordered fields inside content types.
> 2 votes

# Answer
Thanks for the suggestion Stefanos. I did try the paragraphs module and it looked very promising...until I tried to use it with Entity Translation, then everything went to hell in a handbasket. I downloaded a stock version of Drupal and Paragraphs to confirm this was the issue.

I just wanted to leave this for others who stumble upon this. While paragraph looks like a great module, it doesn't meet my requirements for Entity Translation. Also it looks like they're mostly focused on the d8 version, so it looks like the Entity Translation Issue may not be addressed for a bit.

I create two versions for the users to test one using the Multifield module, which worked nice with ET, but in contrast to field collection can't do multi-valued fields inside of itself.

The second version users actually liked better which was just a taxonomy vocab, term reference, and entity reference. So, no new modules and they were able to simplify the structure a bit.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: How to run entityfieldquery on all fields in node that reference users
Is there a way to run EntityFieldQuery on all fields of a node that reference a user?

Thanks!

# Answer
Can you try rephrasing your question? It is not clear what you are trying to accomplish. Do you want to load all nodes that use the same field to reference a user?

If so, you would use the fieldCondition() method. Something like

```
->fieldCondition('field_name', 'target_id', $uid)

```

See https://api.drupal.org/api/drupal/includes!entity.inc/function/EntityFieldQuery%3A%3AfieldCondition/7 for more information.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Exclude the current node in a view with related items in case of multiple contextual filters
Excluding the current node from a display with related items is fairly straight forward. However, in my case there's already another contextual filter (NID) in the game for other purposes.

Adding the exclude functionality on the existing contextual filter isn't working, so I guess an extra contextual filter should be applied in this case. However, simply adding another contextual filter (NID) that's configured to exclude the current node results in no items at all (that moment when you're confronted with the lack of grouped AND or NOT filters for contextual filters).

This situation doesn't feel very unusual to me, so I guess there must be a correct approach for this. My guess is that something must be done with the already existing contextual filter, but can't seem to figure out what exactly.

Can anyone help?

# Answer
> 0 votes
What are the "other purposes" of the first nid contextual filter? Are you taking in the current nid in order to build a relationship to something like a taxonomy term to then get other nodes in the same term?

If so, then the contextual filters should be using different relationships.

# Answer
> 0 votes
https://www.drupal.org/project/views\_exclude\_previous maybe a useful module to consider for this purpose.

It statically caches any previously loaded NIDS on the page and excludes them from displaying in lists.

---
Tags: views
---


title: How to use a tag as a header in Views?

text:
# Question
Title: How to use a tag as a header in Views?
I have a view page where the sort criteria are tag names.

I want to have the appropriate tag-name appear as a `h2` above the content of that type.

Is there an easy way to do this? Or do I have to mess with Twig templates?

# Answer
You can add the `<h2>` tag under Style Settings of your field.

Example:
> 0 votes

---
Tags: views, 8
---


# Question
Title: The responsive menu (Sidr menu) is not working with anchors
I'm using the responsive menus, specifically the Sidr menu, the menu is not working when the paths have anchors. When I do click in a item with anchor the menu is still opened. The toogle in the menu is not working.

Thanks in advance for your help.

# Answer
> 0 votes
The solution to this question is here: https://www.drupal.org/node/2697767

---
Tags: 7, theming
---


# Question
Title: Can Search API filter "Index full entity" be used in Search API views?
I have set up a Solr index for user profiles on my site with the Search API Solr Search. The profiles are pretty complicated-- several relations, lots of fields, and many theme templates to render them with complex logic.

I am trying to speed up the performance of my search views, and I found this option under **Data alterations** on the Solr index:

**Complete entity view**

*Adds an additional field containing the whole HTML content of the entity when viewed.*

I thought I could use this as a cache by saving the rendered HTML to Solr for the user profiles, and then, in my view, I could just display this one item, the complete entity view, instead of having to configure all my fields and views formatting templates.

So, I did the following:

1. At `/admin/config/search/search_api/index/MYSEARCH/fields`, I selected the field for indexing (complete entity view) as **fulltext**.
2. At `/admin/config/search/search_api/server/MYINDEX/edit`, I turned on "Retrieve result data from Solr" as noted in this D.O post.

When I do this, I can now select the "Complete entity view" under **Fields** in the Views UI, but no result (no HTML output) is returned in the display. How can I add the output of the "Complete entity view" in Views?

# Answer
This should be possible. I did the same thing with Search API + Elastic search (No Views module though). And yes it did speed up the results. However, in retrospect I may have been better of using Render Cache module in conjunction with an object cache like Redis and or Memcache.

The main pain point that I ran into doing full storage of HTML in the search server was that nearly every theming/template change required rebuilding the search index.

All that being said, if you want to keep going down this route I suggest using Solr's built in inspection tools to first validate that the user profile HTML has made it into Solr at all.
> 1 votes

# Answer
I had to clear the Drupal cache several times, but after doing so, I was able to index items as described in my original question.
> 0 votes

---
Tags: search, views
---


# Question
Title: Site Access control through a particular user field
I am trying to only grant user the access to the site if one of the user fields have a particular value.

If not, the site should show an access denied.

Is there an efficient way to achieve this?

# Answer
> 0 votes
Let's say there is a specific path you want this rule to apply to, e.g. /special

```
<?php

function my_module_menu()
{

    $items['special'] = array(
        'title' => 'Special Page',
        'page callback' => 'special_page',
        // Permission in next line will be overridden by the check inside the page callback function.
        'access arguments' => array('access content'),
        'type' => MENU_SUGGESTED_ITEM,
        );
}

function special_page()
{
    global $user;
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user');
    $query->propertyCondition('uid', $user->uid, '=');
    $query->fieldCondition('field_special_field', 'value', 'required_value', '=');
    $query->range(0, 1);
    $result = $query->execute();

    if (isset($result['user'])) {
        // User meets the condition
        // Do whatsoever, show special content ..

    } else {
        // Deny access
        drupal_access_denied();

    }
}

?>

```

Make sure to download and enable the Entity API module to use the above code.

---
Tags: 7, users
---


# Question
Title: How can I can I add functionality to my module so that the templates can be overwritten?
How can I can I add functionality to my module so that the templates can be overwrittable like in drupal core. I want to be able to use my module with various themes, but change the required templates.

The only way I have seen to add is via drupal\_get\_path and explicitly specifiying a theme/module.

# Answer
You need to declare your templates by implementing `hook_theme()`, and when needing them in your module uses a render array rendered with the `RendererInterface::render()` method on the renderer service.

Theme, or other modules, will then be able to declare override for your templates like they do for any others.

The theme system overview in Drupal documentation gives more details on this process.
> 1 votes

---
Tags: theming
---


# Question
Title: How to call helper function from my_module.admin.inc file in drush command?
I have some function in the mymodule.admin.inc file that i want call from a drush command and i have done the following below in the mymodule.drush.inc

```
function mymodule_drush_command() {
      $items['custom-cmd'] = array(
         'description' =>'some description',
         'aliases' => array('ccmd'),
         'examples' => array('drush ccmd'),
      );
      return $items;
 }

 function drush_mymodule_custom_cmd() {
     module_load_include('inc', 'mymodule', 'includes/mymodule.admin');
     _helper_func();
 }

```

The helper function is something along the lines of this (mymodule.admin.inc):

```
function _helper_func() {
    //do something
}

```

When i try the module\_load\_include function and i run the drush command i get an error similar to:

```
'PHP Fatal error:  Call to undefined function module_load_include()...'

```

I am unable to find a good resource to help me figure out why the helper function is not called from the drush command.

# Answer
> 1 votes
The `module_load_include()` function can be invoked from Drush; it sounds to me as if some other parts of your Drush setup might not be working properly.

Here's a sample Drush implementation, similar to what you want to do:

```
/**
 * Implements hook_drush_command().
 */
function YOUR_MODULE_drush_command() {
  $items['your-full-command'] = array(
    'callback' => 'YOUR_MODULE_hello_command',
    'description' => dt('Description of your Drush command.'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'aliases' => array('your-alias1', 'your-alias2'),
  );

  return $items;
}

/**
 * Command to download the Chosen plugin.
 */
function YOUR_MODULE_hello_command() {
  // Include your file.
  module_load_include('inc', 'YOUR_MODULE', 'includes/YOUR_MODULE.admin');
  // Invoke your function.
  _helper_func();
  // Show a message to the screen.
  drush_log(dt('Custom command executed.'), 'success');
}

```

You can see a working example in my custom module boilerplate.

# Answer
> 1 votes
I think your hook definition is missing the `bootstrap` part, that's why it doesnt know `module_load_include`. Since you want to call a function from another module, i think you should actually set it to `DRUSH_BOOTSTRAP_DRUPAL_FULL`.

Documentation can be found on the official drush website :).

Or by running `drush docs-commands`.

Good luck :).

---
Tags: drush
---


# Question
Title: EntityFieldQuery return nodes with all terms
I have form that allows a user to filter a list of results. The filter is set using checkboxes. EntityFieldQuery is used to retrieve the results based on taxonomy ids. The problem is that if multiple checkboxes are selected, it returns all nodes tagged with any of the taxonomy ids, while I want only the nodes that are tagged with ALL of the taxonomy ids. This includes terms that are from multiple taxonomies.

These are the definition of the field conditions in my EntityFieldQuery:

$query-\>fieldCondition('field\_section', 'value', $sections, 'IN');

$query-\>fieldCondition('field\_features', 'tid', $params\['features'\], 'IN');

$query-\>fieldCondition('field\_region', 'tid', $params\['regions'\], 'IN');

Basically, when checking on items in the filter it returns MORE items, when it should go the other way.

Does anyone know how to adjust the EntityFieldQuery so it does what I'd like?

Thanks in advance

# Answer
> 0 votes
You can try:

```
foreach ($sections as $section) {
  $query->fieldCondition('field_section', 'value', $section);
}

```

---
Tags: 7, database
---


# Question
Title: How to Get Views field template to be used in replacement patterns?
I'm using a template file like (views-view-field.tpl.php) to modify the output of a specific Drupal 7 Views Field.

I'm trying to modify the field and then use it back in the Views visual editor as a replacement pattern. The problem is it uses the original $output when it is used as a replacement pattern in the other fields' rewritten output (instead of using what I modified in the themed template file).

Is there anyway to do this? I'm trying to avoid going in and theming the other fields just to use the modified first one.

# Answer
> 1 votes
If you make this field the displayed field it will take the theme adjustments. Do your rewrite and replacement patters on this field, put it at the end of the field list and exclude the others. If this field is used as a replacement pattern the theme will not be applied.

---
Tags: views, theming
---


# Question
Title: Use a custom template field even if it's excluded from display
In a Views, I have two field :

* Link field : With 1 to n links to display (excluded from display)
* Body field : Who use the previous link field (via rewrite output and token)

I have created a custom template for display link field like I want.

Here is my problem: When I render my Views, my custom template isn't used for display my links... He use the display function defined in the link field settings.

Is there a way to force View to use my template ? Any suggestions to do this?

Edit : Some screenshot of fields and theme informations

Link field :

Body field :

Theme Infos :

# Answer
To use the custom template for a particular field you should use the template suggestion from **Theme:Information** from advance section of your view, Select the suggestion template form the them info as the screenshot for field NID . Create that template inside the your\_theme/template folder. Don't forgot to clear the drupal cache.
> 0 votes

# Answer
If you make this field the displayed field it will take the theme adjustments. Do your rewrite and replacement patters on this field, put it at the end of the field list and exclude the others. If this field is used as a replacement pattern the theme will not be applied.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I change cardinality (delta) of nodes?
I have a content type, this content type has a Field Collection with cardinality(delta) value 1.

* I want to alter it dynamically, when the node add form is rendered.
* Each node add form has it different cardinality(delta) value.

Please any one help me to solve it in Drupal 7.

# Answer
> 0 votes
You can use form\_alter hook to do it:

```
/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    // Alter your field here:
    // $form['field_collection'][LANGUAGE_NONE][0]['value'];
  }
}

```

To debug form output, you can install Devel module and use dpm() function.

```
/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}

```

---
Tags: 7, hooks
---


# Question
Title: Easiest way to test email notifications locally?
I am making a forum website with email notifications. I need to test these email notifications locally. Ive only ever used MAMP so I dont have much experience setting up dev environments.

What's the easiest way to test Drupal's email notifications locally? Can the Acquia stack do this?

# Answer
You can log the emails, which also brings some sanity to your inbox. Of cause there is a module for that (or two):
> 10 votes

# Answer
Try out Antix. It's easy to set up and works well to test out on a local Drupal install.
> 1 votes

# Answer
A bunch of solutions is documented in the Drupal Community Documentation: Managing Mail Handling for Development or Testing.

Personally I prefer a combination of a local Postfix mail server, the Reroute Email module, and rerouting to a local mailbox. This has the advantage that you don't have to go through the trouble of setting up your local host to successfully send to external e-mail addresses without being rejected as a possible spammer. How to set it up:

1. Install postfix. The default configuration under Ubuntu will work for our purposes.
2. Make sure your relevant `php.ini` is set up to use postfix by containing these two lines. Contrary to the comments there, these settings are not just used on Win32 systems.

```
SMTP = localhost
smtp_port = 25

```
3. Install the Reroute Email module: `drush dl reroute_email && drush en reroute-email`.
4. In the configuration settings for Reroute Email, set the target addres to your Linux username (such as `matt`, no `@hostname.tld` part here). These e-mails arrive in your local mailbox in `/var/spool/` then.
5. Set up Thunderbird to fetch these e-mails: Go to "Edit → Account Settings → Add Other Account… → Type: Unix Mailspool (Movemail)" and use these settings:
    * "E-Mail Address": again use your Linux username (such as `matt`) but determine your hostname (`hostname` command) and add it hostname behind in the format `username@hostname`.
    * "Your Name" and "Account Name": anything will work, this is just cosmetics.
> 1 votes

---
Tags: emails
---


# Question
Title: views preview is different from actual view
The preview of my view looks exactly how I want it to but unfortunately is different when I go to the actual page. Anyway to fix this?

This is using Drupal 8

# Answer
> 1 votes
This happens because Views UI is a part of administrative interface and uses the admin theme to render previews.

If you would use the same theme for admin and front end - you'd see the same style for your View. Although, you should be aware that not all front-end themes render administrative interface good enough - that is why there is an option to use separate themes for admin and end user interface.

To sum it up - there is nothing wrong with how your View's preview is rendered, because preview and the end result are using different themes.

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


title: how to set smtp for drupal

text:
# Question
Title: how to set smtp for drupal
I am working on Drupal 6 my php.ini settings are:

```
SMTP = localhost
smtp_port = 25

```

in module in am using

```
function article_mail($key, &$message, $params) {
  switch ($key) {
    case 'invitation':
      // note: data can be passed to this function in the $params array
      $message['subject'] = t('EMAIL SUBJECT');
      $message['body'] = t('MESSAGE BODY');
      break;
  }
}

```

and in code i use

```
$params = array(  'myVar' => 'data you would like in your message and/or subject',);
drupal_mail('article', 'invitation', 'sanjaydev@xolva.com', language_default(), $params);

```

but it gives

> warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp\_port" setting in php.ini or use ini\_set() in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\benthamdirect\includes\mail.inc on line 193. Unable to send e-mail. Please contact the site administrator if the problem persists.

Can anyone suggest where I am going wrong?

# Answer
> 6 votes
Try the SMTP module to send mails via SMTP:

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.

# Answer
> 1 votes
The error message indicates that no SMTP server is running on your `localhost`. Test this (as shown here), and install and configure a SMTP server like `postfix` if needed. Once your local SMTP server is tested successfully outside of Drupal, come back and test mail sending from within Drupal.

Running an own SMTP server on `localhost` can be meaningful for development, but for production sites, it is quite a headache nowadays to set it up so that it delivers all mail successfully rather than appearing as a spam server to major e-mail providers (GMail, Hotmail etc.). That's where the SMTP module and similar Drupal modules come in: you then can use a third-party SMTP server, which works fine if the e-mail volume is low to moderate.

---
Tags: 6, emails
---


title: Why is my unit test not detected?

text:
# Question
Title: Why is my unit test not detected?
I have a custom Drupal 8 module for which I'm trying to create unit tests by following the instructions at https://www.drupal.org/phpunit.

The path of my module is: `/modules/custom/dev_module`
The path of my tests is: `/modules/custom/dev_module/tests/src/Unit`

More specifically, in the `Unit` folder I have a `DummyTest.php` file with the following code:

```
<?php

namespace Drupal\dev_module\Tests;

use Drupal\Tests\UnitTestCase;

/**
 * My dummy test.
 *
 * @group dummy_test
 */
class DummyTest extends UnitTestCase {

  public function testDummy() {
    $this->assertEquals(5, 5);
  }

}

```

When executing the following commands from the terminal (I'm on Mac OS):

```
 > cd core
 > ../vendor/bin/phpunit --list-groups

```

My group `dummy_test` doesn't show up in the listed groups. Any idea why?

# Answer
> 8 votes
Unit tests must have the following namespace: `Drupal\Tests\dev_module\Unit`.

For complicated reasons, they also don't show up in the right group but they are all in the PHPUnit group.

To run your unit tests with phpunit, just pass the module folder, that also makes it 10x faster for finding the tests:

`./vendor/bin/phpunit -c core modules/dev_module`

---
Tags: 8, testing
---


# Question
Title: Include third party JS library into my drupal module
I want to include this library into my drupal module. Now I have two problems.

1. I wanted to use composer manager to get this library, but it's not available on packagist.org. So, I've tried to put it there manually to do not stuck on it. Path is MY\_DRUPAL/vendor/malsup/jQuery.blockUI/jquery.blockUI.js
2. I want to attach this library via hook\_page\_attachments, but seems I don't know how to define this library in libraries.yml. The problem is that I cannot specify path to folder vendor/ from my\_module.libraries.yml, because vendor/ located in root of drupal.

Could somebody give me an advice?

Thanks in advance.

# Answer
You still put them in the libraries folder (now you can also use a top-level `/libraries`folder).

You need the libraries module, just like in 7.x. I'm also not 100% sure how well it works now in 8.x, in the JW Player module, I'm just using it to detect the location of the files: http://cgit.drupalcode.org/jw\_player/tree/jw\_player.module?h=8.x-1.x#n206
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Redirect to last page after saving new content with rules
Drupal goes normally to the new node after creating or editing it. How to redirect to the last page where the user clicked on the node/add link using rules? I tried different tokens with no success. Here is the rule: Let's say we are on url: sitname/node/133 a user clicks on node/add/announcement Rules: after saving, I need to go back to sitename/node/133 Rules: After saving new content type:announcement

Action: Redirect to page sitename/node/ (token) not sure what to do here

# Answer
> 2 votes
I solved it by taking another route. The original page I wanted to be redirected to is a node type page; on that page, there is a link to create a new node type (announcement).

I didn't mention that the announcement node is referencing the page node through the Entity reference module. To be redirected to the old node type page, I need to use the token \[node:field-new-habit-ref:url\] in the action section of the rule.

---
Tags: rules, redirection
---


title: Creating a simple first module

text:
# Question
Title: Creating a simple first module
I am a total beginner with Drupal and am trying to create a very simple "Hello world" module. I've been following the guide "A Hello World custom page module", but I still get a "Page not found" message.

My directory structure looks like this:

```
    drupal
        modules
            custom
                mymodule
                    src
                     |- Controller
                     |     ExampleController.php
                     |- mymodule.info.yml
                     |- mymodule.routing.yml

```

The module shows up in the admin panel, and I have activated it.

Here's what my routing file looks like:

```
mymodule.content:
  path: '/example'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ExampleController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

```

Here's mymodule.info.yml:

```
name: Hello World Module
description: Creates a page showing "Hello World".
package: custom

type: module
core: 8.x

dependencies:
  - datetime
  - link
  - views

configure: hello_world.settings

hidden: false

# Note: do not add the 'version'  property yourself!
# It will be added automatically by the packager on drupal.org.
version: 1.0

```

And here's the controller:

```
/**
* @file
* Contains \Drupal\mymodule\Controller\ExampleController.
*/

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class ExampleController extends ControllerBase {

    /**
    * {@inheritdoc}
    */
    public function content() {
        $build = array(
        '#type' => 'markup',
        '#markup' => t('Hello World!'),
    );
    return $build;
    }

}

```

When I go to Configuration/Development/Performance and click "Clear all caches" I get this error message:

```
ReflectionException: Class \Drupal\mymodule\Controller\ExampleController does not exist in ReflectionMethod->__construct() (line 128 of core/lib/Drupal/Core/Entity/EntityResolverManager.php).

```

I have tried experimenting with the directory structure, for example moving `mymodule` up directly to `modules` instead of `custom`, but to no avail. What am I doing wrong?

# Answer
> 3 votes
Well, this is embarrassing... By blindly following the guide I forgot to add `<?php` to the beginning of `ExampleController.php`. All these new .yml-files made me forget all about "normal" PHP I guess. Problem solved.

# Answer
> 0 votes
You can check module examples in Examples for Developers module, there are really a lot of useful stuff.

---
Tags: 8
---