title: emails not arriving

text:
# Question
Title: emails not arriving
I have this code to send an email from a form but nothing is arriving and I have no idea why. It looks fine to me

```
function enquiry_form_form_submit($form, $form_state) {
    $strMail = '<!DOCTYPE html>';
    $strMail = $strMail . '<head>';
    $strMail = $strMail . '<meta charset="UTF-8">';
    $strMail = $strMail . '<title>Studiga</title>';
    $strMail = $strMail . '</head>';
    $strMail = $strMail . '<body>';
    $strMail =  "Dear Landlord<br><br>";
    $strMail = $strMail . "You've been sent an enquiry about one of your properties:<br><br>";
    $strMail = $strMail . "Name: " . trim($form_state['values']['name']) . "<br>";
    $strMail = $strMail . "Email: " . trim($form_state['values']['email']) . "<br>";
    $strMail = $strMail . "Telephone: " . trim($form_state['values']['telephone']) . "<br>";
    $strMail = $strMail . "Room information: " . trim($form_state['values']['room_information']) . "<br>";
    $strMail = $strMail . "Room information:<br><br>" . trim($form_state['values']['enquiry']) . "<br>";
    $strMail = $strMail . "<br><br>Regards,<br>Studiga team";
    $strMail = $strMail . "</body>";
    $To_Email = trim($form_state['values']['contact_email']);
    $To_Email = "pamela@gconnect.com";
    $params = array(
        'subject' => "Studiga room enquiry",
        'body' => $strMail,
    );

    $email_from = trim($form_state['values']['name']) . "<" . trim($form_state['values']['email'])  . ">";
    $result = drupal_mail('enquiry_form', 'room', $To_Email, language_default(), $params, $email_from);
    if ($result['result'] == TRUE) {
        drupal_goto('http://studiga.delta-xray.co.uk/enquiry-thank-you');
    }
    else {
        $Msg = "<div>There has been a problem sending the errors Email</div>";
        echo $Msg;
    }
}

function enquiry_form_mail($key, &$message, $params){

  $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';

  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body'];

}

```

Thanks

# Answer
> 1 votes
The drupal\_mail() statement looks fine.

Check your site database logs at "**Admin =\> Reports =\> Recent Log messages (If not available install "Database Logging" module)**" if message is successfully sent or not. If it is failed, then you need to check if your server is properly configured to send an emails from. If not, then you can setup Postfix to send emails from server.

**Updates:** You can also try installing and configuring SMTP module in your Site. The module allows to send email from Drupal Site without setting up Postfix on Server.

# Answer
> 0 votes
There could be many reasons for emails not to arrive, like SPF and DKIM records on your domain. (I've had particular issues with Google Apps domains where the mail would not even reach the spam folder.)

What worked for me in the past is to install the SMTP module. It's a lot easier to install than postfix and allows you to send mails through an external authenticated mail server (so SPF and DKIM become of less importance). You can for instance use this with an @gmail account.

# Answer
> 0 votes
If you're not using Drupal 8 (in which case I am reasonably sure your code would cause errors, but at the very least not work), then it's most certainly a server configuration issue (i.e. you don't have an MTA such as sendmail or Postfix installed). Using the SMTP module would be a quick way to validate your code itself versus spending a few hours to set up and configure Postfix.

# Answer
> 0 votes
$result = drupal\_mail('enquiry\_form', 'room', $To\_Email, language\_default(), $params, $email\_from);

should have been

$result = drupal\_mail('enquiry\_form', 'room', $To\_Email, language\_default(), $params, $email\_from,TRUE);

i was hoping it would do an HTML Email but I see you can't in Drupal 7 without https://www.drupal.org/project/htmlmail

---
Tags: emails
---


# Question
Title: Render node content in page.html.twig level or blocks at node.html.twig level
In a Drupal 8 site design there is expected a view block and a static block in the middle of node content.

I've been trying to figure out how to render node content around the block region (in page.html.twig level), render the block region in the middle of the node content (in node.html.twig level) or any other work around, for ages.

I imagine one way would be to render part of the node content in a view block with contextual filter and other node content fields in the node.html.twig, but I don't know how resource heavy would it be for the system?

If there are any suggestions/solutions anyone here could think of for solving this as efficiently as possible, I'd be very happy to hear about them.

Best,

Alari

# Answer
> 3 votes
So one thing is directly accessing the node object that you have available. E.g. {{ node.some\_field.value }} (which prints the raw value of e.g. a text field, not what you want in most cases) or {{ node.some\_field.view() }} (which views it using the default formatter configuration, you can also provide a view mode or formatter configuration to it).

See also the two related questions that I already added as a comment: Render a node field inside page.html.twig AND Render image field from node in page.html.twig.

As you found out yourself, you can also use blocks for this. However, using views for that is a bit backwards. Views executes a query. So what it does is get the node from the already loaded ID, then does a query to get the node ID and then gets the node again for that Node ID ;)

As an alternative, blocks in D8 support context. So they can get things from the site injected and use it directly. See https://drupal.stackexchange.com/a/188629/31 for some explanation on this. You can implement a custom block yourself and print out what you want, or you can use the block that ctools provides that allows you to view a node with a specific view mode.

# Answer
> 1 votes
I believe twig doesn't let us use php. So I guess the only way is to use a module.

### Display Suite

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

Display suite lets you add blocks as fields.

### Panels

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Basically an alternative to Display Suite. Both of these modules are great. Panels has an easier create a layout system than Display Suite.

---

With either of these modules, you could do something like this

Field A

Block or Block View

Field B

# Answer
> 1 votes
Also, if a field has multiple values, the syntax for it in page.html.twig is node.some\_field\[x\].value. X is for the position in field value array.

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


title: Add active-trail class to menu

text:
# Question
Title: Add active-trail class to menu
I am working on a drupal 8 project. I am building menus from drupal. My menu would be like the following structure:

-parent

--child 1

--child 2

--child 3

when i go to a page which is child 3, and the menu will also appear on that page. i would like to set active class on both child 3 and also parent. Is there any way to do so? Thanks.

# Answer
That happens automatically, at least by default for themes inheriting from Classy. See https://api.drupal.org/api/drupal/core%21themes%21classy%21templates%21navigation%21menu.html.twig/8:

```
  {%
    set classes = [
      'menu-item',
      item.is_expanded ? 'menu-item--expanded',
      item.is_collapsed ? 'menu-item--collapsed',
      item.in_active_trail ? 'menu-item--active-trail',
    ]
  %}
  <li{{ item.attributes.addClass(classes) }}>

```

So, make sure you are inheriting from Classy (recommended) or duplicate some of this logic in your theme.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Programatically adding new CKeditor instance
What is the trick to ckeditor in D8? It's woefully under documented and CKEDITOR / CKEDITOR.instances seemingly return nothing, despite showing multiple instances of ckeditor instances available. CKEDITOR.replace() seems to give a config error (missing 404 js files) when you try to target an element.

I can target and get data back for CKEDITOR.dom.element.get('edit-comment-body-0-value') but once try to use getEditor(), it automatically returns NULL.

# Answer
> 3 votes
You're not supposed to use the CKEditor API directly. You could do that if you want to use CKEditor on something you control. But your DOM ID (`edit-comment-body-0`) indicates you're trying to do this for a "Formatted text" field in Drupal 8, which uses the filter system. If you'd want to attach CKEditor manually, use the JS API provided by `core/modules/editor/js/editor.js`.

The integration between Drupal 8 and CKEditor is very solid/deep, in that Drupal 8 automatically configures CKEditor to match the text format's filter settings. And that integration is not tightly coupled to CKEditor: there's the Text Editor (`editor`) module that allows any text editor to integrate in a similarly deep way. But it means you should always use the APIs that `editor` provides.

For API docs, see:

For the concrete relevant code, see `TextFormat`, `editor_element_info_alter()` and `\Drupal\Editor\Element::preRenderTextFormat`.

---
Tags: 8, wysiwyg
---


title: Ckeditor link text to file

text:
# Question
Title: Ckeditor link text to file
I'm creating a content type on Drupal 8, which will contain a text that's linked to PDF file.

In Drupal 7, it was just easy with some useful modules. Is it possible to link a text to a PDF file using CKEditor in Drupal 8?

# Answer
You can upload file separately and after that add the link to this file. Or you can use module IMCE to upload files in WYSIWYG and add link on them easily.
> -1 votes

# Answer
This Drupal 8 module does exactly that, in a tightly integrated way: https://www.drupal.org/project/editor\_file
> 1 votes

---
Tags: 8, wysiwyg, files
---


# Question
Title: Add specific CSS class with Semantic Views
I am searching for days now and don't find the solution so I exposed my problem here.

I am under Drupal 7 and I don't find an issue for this problem.

Here is the purpose: I created content with one specific field, a boolean, so when it's checked i want to add a class to an existing view. I explain.... Once I created content explained before, I create a view for it (with semantic views) and save! It works perfectly but....what I want to do is that when I check the boolean (in the content) it adds me a new class to the article () see figure below:

In a content (created with a custom content type), I check this checkbox:

And so:

became:

From now the source code looks like this:

Thank you very much for your answers!

# Answer
> 0 votes
This is possible to accomplish by overriding the View's template. You would have to create a custom Views tpl file with logic for adding a custom class based on a field value. Unfortunately you can not do this by simply using Views UI.

**How to achieve this:**

1. Add your Boolean field to the View and "Exclude from Display". Keep the default formatter of the field.
2. Create a custom View template. Click on *`Theme: Information`* in `*Advanced settings*` of your View. You'll see template suggestion for overriding different parts of the View. Here you are looking to override the *`Style Output`* of your View.
3. Click on *`Style Output`* link and you'll see the default content of .tpl file. Copy the code and paste it in a file named `*semanticviews-view-unformatted--machinenameofyourview.tpl.php*`. The name of the file that you should use will be listed in step #2, right after the one that it highlighted in bold, so you'll be safer by just copying and using that. Save this file in your current theme's `template` folder.
4. Now go back to the *`Theme:Information`* dialog of your View and click `"Rescan Template Files"` \- you'll see that your new template is now detected by the View as it will become highlighted in bold. Click `OK` \- now you told the View to use your new template. Save the view.
5. Open your new template file and paste the code below in it. You can replace the content of new template with the code pasted below, or just find the section // ADDED and paste it in the right place. `*Section //ADDED will define the logic for adding custom class when Boolean field is checked.*`
6. Replace the field\_field\_boolean w/ field\_field\_yourfieldname. *Note:* double field\_ is necessary here. Also, replace the name of the class to your desired class name.

.....

```
<?php
/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <<?php print $group_element; ?><?php print drupal_attributes($group_attributes); ?>>
    <?php print $title; ?>
  </<?php print $group_element; ?>>
<?php endif; ?>
<?php if (!empty($list_element)): ?>
  <<?php print $list_element; ?><?php print drupal_attributes($list_attributes); ?>>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (!empty($row_element)): ?>

  <?php // ADDED CODE ?>
  <?php
        $custom_class = '';
        if (isset($view->result[$id]->field_field_boolean[0]['raw']['value']) && $view->result[$id]->field_field_boolean[0]['raw']['value'] == TRUE) {
            $custom_class = 'my-custom-class';
        }
        $row_attributes[$id]['class'] = $row_attributes[$id]['class'].' '.$custom_class;
    ?>
  <?php // END OF ADDED CODE ?>

  <<?php print $row_element; ?><?php print drupal_attributes($row_attributes[$id]); ?>>
  <?php endif; ?>
    <?php print $row; ?>
  <?php if (!empty($row_element)): ?>
  </<?php print $row_element; ?>>
  <?php endif; ?>
<?php endforeach; ?>
<?php if (!empty($list_element)): ?>
  </<?php print $list_element; ?>>
<?php endif; ?>

```

.....

---
Tags: 7, views
---


# Question
Title: JSON through Services View- Authenticating through Parameters when accessing JSON through external app
My Drupal site is generating JSON through Views. I am using Services for that.

It is something like this:-

```
http://www.asite.com/api/views/all-date.json

```

Now the problem is that I want to restrict anyone from writing that URL in the any browser and retrieving all data.

Do you think there is a way to authenticate it?

Probably, in my external app, when I am accessing the data, I can add parameters to it so that it can only send data when it has right authentication.

Something like this:-

```
http://www.asite.com/api/views/all-date.json/?username=me&password=mine

```

I'll be grateful if you could help.

# Answer
There exit many ways of authentication through services module.

The easiest is to use session authentication by authenticating the user using his **username & password**, Then let the app send the cookie header in each request with the session id like **COOKIE: SESS\_ID:SESS\_name**.

Or use that module that seems matching your approach a lot services\_basic\_auth

Another way is to authenticate the app itself by letting the app get an access token using a secret app id and password created on the website. using oauth2

Examples for auth methods
> 0 votes

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


title: Drupal Services OAuth

text:
# Question
Title: Drupal Services OAuth
I have been working on this issue for a couple weeks now, and I can't find a solution for the life of me. The fact that I have found no decent documentation (on Drupal's website, or anywhere else) is no help either. And the questions already on here are outdated (Services 2.x).

I'm trying to create a REST service for a Drupal Commerce backed site. For now all the service must do is allow for basic CRUD operations on the Order resource, and be secured with OAuth, OAuth 2.0 isn't necessary. It must also be called with a script on a server, so login re-directs are impossible (everything is done with 2-legged authentication).

The current stack is:

* PHP 5.3.15
* Drupal 7.15
* Commerce Kickstart profile (7.x-2.0-rc1)
* Services 7.x-3.2
* OAuth 7.x-3.0+18-dev
* OAuth Authentication 7.x-3.2
* REST Server 7.x-3.2
* Commerce Services 7.x-1.x-dev (This is the module I have added my custom Order code to)

I can kind of get the Retrieve/Index functions to work for Orders if I use an OAuth PHP library and just call the token request every time (I'm not even sure what's going on there, except that it authenticates...). If I try to POST to Orders and create an order though, I get 406 with the script, and 401 when I try a direct POST request from the REST Console in Google Chrome, even when OAuth is disabled.

This has made debugging a nightmare since I have no idea what's going on inside my create function. I tried stripping it of its order creation logic and just echo back the request payload. Still get the 406/401 errors.

I assume I get the 401 errors because orders require a user authentication (even if OAuth is turned off for the service).

I don't understand why I'm getting the 406 errors though. I accept application/json, which is what my REST server is set to return.

Orders were not being created even before I commented out the order creation logic. (Which I use elsewhere in the site effectively.)

Appreciation in advance.
-T

# Answer
**Get** requests did not need session authentication, **POST, PUT, DELETE** require session authentication to know the user and check if he has right permissions to complete the request or not.

Oauth authentication have many types of auth you must ensure that you are authentication the user not the an app (for example) so the request is authorized to complete.
> 1 votes

---
Tags: commerce, services, users, 8, authentication-authorization
---


# Question
Title: How to change the main menu event from a default click on it to the navigation of the mouse arraow?
How to change the main menu event from click to navigation? I want to make submenus of the main menu to respond on mouse arrow navigation not on a click which is default. What is a rational way to change it? Does it depend on a patriclular theme?

# Answer
Use contributed module like:

> Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)
>
> Three styles/types of menus are currently possible: horizontal, menus drop down; vertical, menus fly to the left; vertical, menus fly to the right. There is a handbook page that provides a list of sites that use Nice menus.

> Mega menus are a type of drop-down, which seeks to overcome some of the usability drawbacks of traditional drop-downs. Hierarchy of your navigation is made visible all at once and the amount of clicking, searching, and navigating is reduced.
>
> This module allows you to build mega menus by leveraging jQuery and the existing Drupal menu system. Megamenu takes a Drupal menu that is 3 levels deep, and converts it into a categorized 3-level mega menu, which is placed into your site as a block.

> TB Mega Menu allows you to create a mega menu with an innovative back-end user interface and synchronized with Drupal core menu.
>
> We strive for more improvement each release, and your feedback on this module is extremely important to us.
> 1 votes

---
Tags: navigation
---


title: Data not received on server in ajax

text:
# Question
Title: Data not received on server in ajax
I'm trying to post data from ajax to php page which I made in the hook\_menu, called "handler". So I have "domain.com/handler" which I try to do this in it:

```
function handler(){
  print_r($_POST);
}

```

and the hook looks like this:

```
$items['handler'] = array(
  'title' => 'Handler',
  'description' => 'handler for File Upload',
  'page callback' => 'handler',
  //'access arguments' => array('access my_module_name via ajax'),
  'access arguments' => array('access example ajax'),
  'type' => MENU_CALLBACK
);

```

and on my js file i do this:

```
$.ajax({
  url: "/handler",
  type: "POST",
  dataType: "json",
  data: {"name":"John","location":"Boston"}
})

```

and its wrapped inside Drupal.behaviors.mymodule = {...} when I run the ajax, the response I get is an empty array. why don't I receive the data?

# Answer
> 0 votes
`$_POST` is:

> An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

That's not what you're doing. To receive JSON data in PHP you need to use:

```
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

```

Or change the data type of your AJAX request to one of the values that will result in `$_POST` being populated.

---
Tags: ajax
---


# Question
Title: Is there a way to hook on cache clearing?
For a big institution website, with heavy caches, I'd like to generate caches as soon as possible, so that no user may arrive on cache generation...

I have a cron set all minutes that does it, by executing a few functions and requesting critical pages, but what I'm looking for is **a way to know when the cache has just been cleared**, preferably a hook, so I can launch this generating-functions.

Any idea ?

# Answer
There isn't in Drupal 7.x but this was added as a core hook, hook\_rebuild in Drupal 8.x after enough people requested it. There may be a better way to solve your problem in 7.x though -- you're trying to initiate some kind of cache warming functionality right after cron clears the cache, correct? Another way to approach this would be to use Elysia cron which has a number of significant improvements to how cron operates but two that might be relevant to your use case are:

> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.
>
> * Set the timings and frequencies of each cron task (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration. ...
> * Change the priority/order of task execution. ...

You can use this module to have finer control over how your cron runs to help resolve the stale cache issue. Specifically, you could add a hook to your rebuild functions to cron and then using Elysia cron, set these operations to run immediately after the cache clearing operation.

It also sounds like you might be having issues with cron running to frequently leading to the cache getting recreated too often. If that is the case, you can set the specific cache clearing operation in Elysia cron to run at a different rate than the rest of your cron operations, so for example search indexing would update every 5 minutes but the full cache clear would only run every 6 hours, etc.

> Fine tune cron cache management : drupal cron will invalidate variable cache every cron run, and this is a great performance problem if you have a frequently called task. Elysia cron optimize cache management, and doesn't need to invalidate cache.
> 8 votes

# Answer
The way to do this is to use `hook_flush_caches` in combination with `register_shutdown_function`. Example code:

```
/**
 * Implements hook_flush_caches().
 */
function mymodule_flush_caches() {
   // After caches are cleared we will run mymodule_cache_rebuild()
   register_shutdown_function('mymodule_cache_rebuild');

   // We don't want to add any custom cache-tables, so just return an empty array
   return array();
}

/**
 * Rebuild expensive cache items that need to be rebuilt immediately.
 */
function mymodule_cache_rebuild() {
  // Do the cache rebuild work here
}

```

Using `register_shutdown_function` means that our cache-rebuilding function will be called *after* the caches have been cleared. We are abusing `hook_flush_caches` in a way that it was never intended to be used, but this should do exactly what you need.
> 13 votes

# Answer
No, there isn't. Not really. At least not in 6 or 7. Assuming 7:

If you will look at `drupal_flush_all_caches()` you will see it invokes `hook_flush_caches()`. This hook is meant to:

> "add cache table names to the list of cache tables that will be cleared by the Clear button on the Performance page or whenever drupal\_flush\_all\_caches is invoked."

It would be tempting to simply make your module's hook go last and write code there. But let's look again at `drupal_flush_all_caches()`. Actual deletion happens like this:

```
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
    cache_clear_all('*', $table, TRUE);
  }

```

It means that all hooks are fired *before* anything gets really cleared. There is only one function called after actual deletion, `_system_update_bootstrap_status()`, but it only calls `hook_boot`, `hook_exit`, `hook_watchdog` and `hook_language_init` \- hooks you don't want to implement only to provide cache-clear-dependant functionality.
> 11 votes

# Answer
Broad strokes here:

While there isn't a hook out there in pre-D8, you could write your own database backend based upon the standard `DrupalDatabaseCache` one and then write any or all sorts of logic into your `clear()` function. A quick look would suggest this to be a reasonably straightforward in D7 (just copy the class to your custom name and modify it etc by throwing in a `module_invoke_all()` as appropriate) and with the cache\_backport module would even work in D6. Then point any cache bins you want fancified on clear and you should be on your way.
> 8 votes

# Answer
If you look at the source for `drupal_flush_all_caches()` and `clear_cache_all()`, you will see that no hooks are invoked post clearing, which is a pretty bug bummer.

It is very difficult to guarantee that a user will never have to wait for some cache entries to be built, so I try to avoid full cache clears as much as possible.

One method that really helps is to form alter the performance page to wire up a submit handler that just clears the forward facing caches, and doesn't touch the menus, registry, and similar core caches. I have had good results with this, as menu and registry rebuild take up about half of the time for a full cache rebuild.

The other thing that I have a drush script that does a `drupal_http_request()` on all of my URLs (not just the important ones) so that everything gets cached. How this is done varies by site. Sometimes I can just EFQ the published nodes, and build up URLs that way. Other times, you can query the XML sitemap tables to get your URL. I then call this from my system cron as often as I need.
> 3 votes

# Answer
This may not be suitable for everyone, and may not be quick enough for the OP — as it is only triggered on the next page initialisation. However, it helped me with triggering code just after a "cache clear all" that wasn't time sensitive.

> Obviously `HOOK` needs replacing with your own module name.

```
/**
 * Implements hook_init().
 */
function HOOK_init(){
  // if there is no cache_not_empty defined, define it
  // and then trigger our cache cleared code
  if ( !cache_get('HOOK_cache_not_empty') ) {
    cache_set('HOOK_cache_not_empty', TRUE);
    foreach (module_implements('cache_cleared') as $module) {
      module_invoke($module, 'cache_cleared');
    }
  }
}

/**
 * Implements hook_cache_cleared().
 */
function HOOK_cache_cleared(){
  // do what you need here, in which ever module.
}

```

If you have a specific bin you need to target, the above could be modified to support that, as long as the entire bin gets emptied at the point of your cache clear.

`hook_init` is only executed for non-cached pages. Although because a full cache clear should mean no cached pages, this shouldn't cause a problem. However, external caching systems like Varnish will get in the way of this triggering, and will mean it'll only occur when the next proper request reaches back to Drupal.

> It should also be noted that depending on your caching system — on exactly when a `cache_set` becomes available to all concurrent users — that this hook could be triggered multiple times concurrently, especially if you have large numbers of users.
> 2 votes

# Answer
Couple of options:
https://www.drupal.org/project/cache\_graceful might be exactly what you want.

https://www.drupal.org/project/apdqc has 2 hooks that fire on a cache clear allowing you to alter the clear `drupal_alter('apdqc_cache_clear', $cid, $wildcard, $this->bin, $caller);` and after allowing you to react to the clear `module_invoke_all('apdqc_cache_clear', $cid, $wildcard, $this->bin, $caller);`. Get APDQC working correctly and set `$conf['apdqc_call_hook_on_clear'] = TRUE;` in your settings.php file & then the hooks should be called whenever a cache clear is done.
> 1 votes

# Answer
I had a similar need, where a client wanted to flush both Drupal and Varnish caches when they hit the "flush all caches" button. I hijacked that menu item to do so.

This won't hit any cache clears on cron or anywhere else - just on the menu link.

```
/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  if (isset($items['admin_menu/flush-cache'])) {
    $items['admin_menu/flush-cache']['page callback'] =
      "_mymodule_custom_flush_cache";
  }
}

/**
 * Hijacks the "flush all caches" button in menu
 */
function _mymodule_custom_flush_cache() {
  /**
   * Clear varnish, or other logic here
   */
  admin_menu_flush_cache(); //Run the normal cache clearing stuff
}

```
> 0 votes

# Answer
You may like to try https://www.drupal.org/project/recacher — it uses Cache Expiration module to detect expired pages and then re-cache only those pages using the excellent HTTPRL.
> 0 votes

---
Tags: 7, hooks, caching
---


# Question
Title: How to implement access permissions per individual field and individual nodes?
I know there is https://www.drupal.org/project/field\_permissions module, which allows to set field permissions per role, however what I need is to provide each individual field access permissions. As put on https://www.drupal.org/node/1376182

> It looks that there is no module allowing to restrict access to certain files / images per role. What I think about is having checkboxes beside each file/image where to select the roles to have view access to the according entry.

I can't believe this was not implemented before, so hopefully someone can point out a viable solution.

Edit: I've got couple responses confused about what I wanted, so I believe I have to elaborate little more.

Field Permissions set role permissions for the field across all the nodes. What I am looking for is role permissions for individual field PER NODE. For example, an admin for Drupal 7 site could edit node 1 and make the file attached to it viewable to role "subscriber", but that wouldn't change any permission for another file attached to node 2. I hope it is now clear.

# Answer
> 1 votes
Not sure if it is going to be the best/most elegant solution, but here is "an" approach that might work:

* Use the Entity reference module to replace your file field in your existing content type with a reference to some other content type (say `Resource`).
* Attach your files to nodes of content type `Resource` (so not in your already existing content type nodes).
* Use the Content Access module to implement the refined access that you are looking for, but applied to that `Resource` content type.
* Create some testcase(s) to verify how that refenced `Resource` node is going to be shown in your original nodes.

Get the idea? Pretty basic Drupal techniques (to KeepItSuperSimple, aka KISS).

I haven't tested it (yet) while writing this answer, but I bet functionally it will behave exactly as what you'd want. And guess what: no need for the field permissions module to make this work.

FYI: the above is a D7-equivalent of how I used to create such kinds of related content in D6 already (also using the Content Access module, and I believe in D6 it was "node reference" or something like that).

# Answer
> 0 votes
I not exactly understand your request. With field\_permission you can set access permissions for each individual field. For example you can decide that a role can view and edit a field, instead another role can only view the same field.

# Answer
> 0 votes
I solved this problem using some code in the theme templates. Still I believe there should be a Drupal module for this specific purpose. There are per individual node permissions (not per content type, but individual nodes), so I don't get why there shouldn't be per individual field permission modules.

---
Tags: entities, files
---


# Question
Title: Link a Page to another Page using Views and taxonomy
I have a Page created using a View using a Content Type called Sectors, which displays rows of images with a title underneath the image. The Sector content type has the fields - Title, Image, Sector Category (uses a Taxonomy). A Sector can have many Projects.... so.....

When the user clicks on the Sector Image or Title, i want my site to go to another Page which is created using a View and display all the Projects belonging to that Sector using the Sector Category field (which is a field on both Sector and Projects content type, passed to it from the previous Sectors page), to select all the Projects that are held in the Projects Content Typle - which has fields Title, Image, Sector Category.

How can I link the 2 views?

# Answer
You first need to create your other page, using Views, with a path pattern similar to the following:

```
projects_by_sector/%tid

```

This page can then be configured to display only content of type Projects and the fields you need (Title, Image, Sector Category, etc). Most importantly, you need to configure a contextual filter with the following configuration:

* For the "Content: Sector Category" field
* "Provide default value"
* "Raw value from URL"
* "Path component" =\> 2 (this follows from the example URL above)

Now back in your existing Views page for the Sectors list, you need to do some field rewriting. This can be done in a number of ways, the easiest would be to add the Sectors Taxonomy reference again as a field and do the rewriting on that field. You can do these using the following steps:

* Add the "Content: Sector Category" field
* Save with the default configuration
* Rearrange your fields and move the new field below/after the "Content: Title" field. This is important so that the replacements token ***\[title\]*** will be available for the rewriting.
* Hide the "Content: Title" field by selecting "Exclude from Display" on its configuration
* Configure the new "Content: Sector Category" field
* Select "Plain text" as "Formatter"
* Expand "Rewrite Results"
* Select "Rewrite the output of this field"
* Enter the following in the "Text" textarea to use the title of your sector
***\[title\]***
* Select "Output this field as a link"
* Enter the following as the "Link path"
***projects\_by\_sector/\[field\_sector\_category-tid\]***

This is a rough idea, you need to tune your views page accordingly, but the end-result should be what you asked for. Hope this helps!
> 2 votes

---
Tags: views
---


# Question
Title: How to change the format of Last seen: in author pane in advanced forum?
I have installed Advanced forum and Author pane module. Now, I did found the option of date format for Joined:\__________, But not able to find the date format for Last Seen:\________, The Last seen option shown very granular details like, Last Seen: 1 min 20 sec ago, I just want like,

```
Last Seen: 1 min ago

Last Seen: 2 hr ago

Last Seen: 1 day ago

Last Seen: dd/mm/yyyy

```

# Answer
Here's what you need to use:

```
function YOUR_THEME_preprocess_author_pane(&$variables) {
  // Get the number of seconds since last login.
  $time_since_last_login = REQUEST_TIME - $variables['account']->access;
  // Custom override of the "last_active" variable.
  //
  // This is just an example; add your rules here.
  if ($time_since_last_login < 120 * 60) {
    // Show 2hr ago for any interval within last 2 hours.
    $variables['last_active'] = t('2 hours ago');
  }
  else {
    $variables['last_active'] = format_date('short', $variables['account']->access);
  }
}

```

Just add your custom time formatting rules.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Warning: file_put_contents(temporary://): failed to open stream
I get this message from Drupal:

> Warning: file\_put\_contents(temporary://file8vyLsO): failed to open stream: "DrupalTemporaryStreamWrapper::stream\_open" call failed in file\_unmanaged\_save\_data() (line 1900 of /home/donatelo/public\_html/thenameofthesite.com/includes/file.inc).
>
> The file could not be created.

I don't know what I did to cause this, can anyone help me?

# Answer
Make sure your temporary folder exists and is writeable.

See the file system settings at:

`admin/config/media/file-system`
> 11 votes

# Answer
The error happens, because your temporary directory is not writable by your web server user.

Check for details in *Status report* at: `/admin/reports/status`

If you're using `drush`, this may fix it:

```
drush vset file_temporary_path /tmp

```
> 1 votes

---
Tags: 7, files
---


title: File issues after importing Drupal site

text:
# Question
Title: File issues after importing Drupal site
I recently tried to move my Drupal site to a new server using this page: Moving Drupal 7 site to a new server.

But now the style doesn't seem be loaded and more importantly I get this error on every page in the site (even on the frontpage):

> Warning: file\_put\_contents(temporary://filef76T9k): failed to open stream: "DrupalTemporaryStreamWrapper::stream\_open" call failed in file\_unmanaged\_save\_data() (line 1900 of /Library/Server/Web/Data/Sites/Default/drupal/includes/file.inc).
>
> The file could not be created.

Any ideas what this could be about?

# Answer
> 8 votes
It sounds like your temp directory is either wrong, or isn't writable.

Visit "admin/reports/status" and fix any problems that are there.

Then visit "admin/config/media/file-system" and make sure the temp directory is set properly and is writable by the webserver.

# Answer
> 0 votes
The error happens, because your temporary directory is not writable by your web server user.

You may check that in admin panel by going to *Reports* and *Status report* at: `/admin/reports/status`.

To fix it, you've to got to *File system* in *Configuration*, then change your *temporary directory* to point to your writable directory. If that's correct, then make you set the right permission on it, e.g.

```
sudo chmod 777 /tmp

```

and the same for default files folder:

```
sudo chmod -R 777 sites/default/files

```

If you're using `drush`, check which folder is set currently by:

```
drush vget file_temporary_path

```

Then to fix it, try:

```
drush vset file_temporary_path /tmp

```

---
Tags: 7, migrations, files
---


# Question
Title: CKEditor simple image upload functionality
I'd like to have a simple, one-click, image upload functionality with CKEditor. I'm using D6 and CKEditor 3.6.1. I do not want a server file browsing functionality, only uploading images from the user's own computer.

I've done a thorough search on this subject and have tried different suggested approaches. It seems like the solution that best suits my needs is installing the IMCE module and the CKFinder plugin for the CKEditor module. So I did just that, and followed the installation instructions found here: http://drupal.org/node/738092

The uploaded image manages to get to the destination folder on my server, but when I open CKEditor's 'Image properties' dialog and hit the 'Send to the server' button, nothing changes on the UI.

What I wish to happen is for CKEditor to close the 'Image' dialog and insert the uploaded image into the textarea.

Here are some screenshots to better explain my situation:

**\- Uploading a file from my desktop**

**\- Expected result - 'Image' dialog automatically closed and image inserted to textarea**

**\- Actual result - 'Image' dialog stays open and nothing changes**

Does anyone ever implemented an image upload functionality this way? Is there a better way to get what I want?

# Answer
If you ever get to D7, this module does exactly what you're looking for:

One Click Upload module

> Button for BUEditor and CKEditor which allows upload files in one click.
>
> Features
>
> * Upload images and insert into editor image code
> * Upload files and insert into editor link code
> * Multi-upload files and images
> * Integration with image styles
> * Editable html templates
> 4 votes

# Answer
Now CKUtils Image plugin is available right for this thing! See also another plugins from set, for example to upload previews with link to full-sized image.
> 1 votes

# Answer
You could use the One time Upload Module in order to full fill your need if you wish to use Drupal 7 version.

> Features:
>
> 1. Upload images and insert into editor image code
> 2. Upload files and insert into editor link code
> 3. Multi-upload files and images
> 4. Integration with image styles
> 5. Editable html templates

For more detail about the module you could read the README.txt of this module.
> 1 votes

# Answer
Simply try the the following plugin which allows you to directly upload files to the server without needing any file browser. Great and simply the best experiences you will get!

http://doksoft.com/soft/ckutils/index.html
> 0 votes

# Answer
You can use the dragndrop\_uploads module. It provides versions for both Drupal 7 and Drupal 6, the latter are just hidden behind the "View all releases" link, probably because they are unsupported now.

Despite the name, it's not a generic file upload module but made for image uploading into rich text editors. From the project page:

> The Drag'n'Drop Uploads module adds the ability to drag an image from your local filesystem, drop it onto a node body textarea and have the file automatically uploaded and referenced in your node. \[…\] \[It provides\] Support for the WYSIWYG module.
> 0 votes

# Answer
To upload an image, simply drag-and-drop from your desktop or from anywhere. You can also copy the image and paste it on the text area using ctrl+v.
> -3 votes

---
Tags: 6, media, wysiwyg, files
---


# Question
Title: Warning: Invalid argument supplied for foreach() in taxonomy_field_formatter_view()
My Drupal installation has some warnings, I tried several patches, but none of them works for me. These are the warning messages:

> Warning: Invalid argument supplied for foreach() in taxonomy\_field\_formatter\_prepare\_view() (line 1677 of modules/taxonomy/taxonomy.module).
>
> Warning: Invalid argument supplied for foreach() in taxonomy\_field\_formatter\_view() (line 1600 of modules/taxonomy/taxonomy.module).

It looks like I get those warnings randomly, I can't find a specific handling.

I think I get this message when I create/edit a node.

# Answer
> 1 votes
As per this post, this warning can be eliminated by editing the field on each file type which is having a field and unchecking *Override in WYSIWYG* (at `/admin/structure/file-types`). This happens because term reference doesn't support overridable in the WYSIWYG.

This issue at Drupal.org: #2062721: Add a white list of file fields that can be overwritten when the file is added in the wysiwyg, aiming to solve that issue. At time of writing, there is still some patch which is in *Needs review* status.

# Answer
> 0 votes
Actually it is using `hook_field_formatter_prepare_view`, it checks if the term which has been passed to it exists or not. So please check the term which are going through it, if it exists or not.

---
Tags: 7, entities, taxonomy-terms, media, files
---


# Question
Title: How to find the right data selector in Rules Components?
In Drupal 7, I have set up a rule to automatically close blog comments after two weeks. That works well.

Now, I am trying to have a block displayed on the blog entries when comments are closed. For this, I am using the Rules block visibility module.

I have set up the rule component as per the strict instructions of the module's "readme.txt" file. **Without any condition,** the export of the component gives this:

```
{ "rules_set_comments_closed_blocks_after_blog_entry" : {
    "LABEL" : "Display Comments Closed block on blog entries",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

The problem I have is with the condition. I cannot find the right data selector in the Data Compare section.

If, on the other hand, I create a rule to display a system message on the site when comments are closed, I do find the data selector item "node:comment" and comparing its value to "NOT 2" (meaning not open) makes the message display only on blog entries with closed comments.

The above exported component works, but on all blog entries whether the comments are closed or not. I just need to add the condition to differentiate nodes with closed comments from those with open comments.

I have tried "entity" has field, entity is of type, etc. But, in components, the list of data selector is still very limited. In fact they are limited to site or current user items.

How can I expand the list of data selectors so that I find my "node:comment" (or similar) selector?

Any help on this is greatly appreciated. :)

# Answer
Head over to the **settings** of your Rules Component, and specify "Node" as an extra parameter (on top of the 3 you already have in place). You can find "Node" within group "Entity".

After doing so, try again to add "Node" as your data selector, more specifically "Node:comment" (for which you want to test if its value is "0"). This time (after you added that extra parm) it should show up as a data selector.

Here is a sample Rules Component (in export format) that does something similar (it has an extra condition for "uid=1", which is probably not what you want).

```
{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false },
      "node" : { "label" : "Node", "type" : "node" }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } },
      { "data_is" : { "data" : [ "node:comment" ], "value" : "0" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

If you just import the above Rules Component, it already has that "Node" as an extra parameter.

**Note**: if you get unexpected errors (after enhancing your Rules Component as suggested above), then enable Rules debugging (so see the Rules debugging log). You can do this via `/admin/config/workflow/rules/settings`
> 1 votes

---
Tags: 7, rules
---


title: Views Send with multiple email fields

text:
# Question
Title: Views Send with multiple email fields
I've just got Views Send to work. I have a custom node type, with two email fields. One field contains a~single email address, the second field can contain more email addresses. Using Views Send, I can send mail to either field (even when one field can contain more email addresses).

The question is, can I use Views Send to send an email to both fields at the same time? Now I can only select one field containing emails. Sometimes it is necessary to send the same mail to both fields.

Yves

# Answer
> 0 votes
I had a look at this interesting module and I am afraid I didn't see a way to do this. I tried Views rewriting, to collect all email addresses from first and second email field into a third one. Standard Views presented the new dynamic field fine... But, this is not supported by the Views Send module. It seems like it would need the data available in the database, and not dynamically generated.

If you want to have that working in an easy way, you could try adding a Computed Field to your content-type. This computed field would then store all the emails from your first and second field. And this concatenated string would be available to Views Send.

Would that be a way out for you? If so, here is an 'draft' version for the code to put in the "Computed Code (PHP)" textarea:

```
$field_main = field_get_items($entity_type, $entity, "field_main");
$field_additionals = field_get_items($entity_type, $entity, "field_additional");

if(isset($field_main[0])) {
  $emails[] = trim($field_main[0]["value"]);
}

foreach($field_additionals as $field_additional) {
  if(trim($field_additional['value']) !== '') {
    $emails[] = trim($field_additional['value']);
  }
}

$entity_field[0]["value"] = implode(', ', $emails);

```

Voila! Your computed field is readily available in your Views and Views Send containing all the emails from both fields.

---
Tags: views, emails
---


# Question
Title: Fatal error: Call to undefined function media_filter
I've upgraded Media module from 2.0-alpha2+6-dev and 2.0-beta1, however now I've the following error on some random pages:

> ( ! ) Fatal error: Call to undefined function \`media\_filter()\` in my\_module.module on line 224

My code in `hook_field_formatter_view` in my module is:

```
$element[0]['#markup']
  = '<div class="my-formatter-slide-down-container"><div class="text-summary ' . ($settings['hide_summary'] ? 'hiding' : '') . '">'
  . media_filter($text_summary)
  . '<a href="' . $read_more_link . '" class="read-more">' . $read_more_text . '</a>'
  . '</div></div>';

```

The code of that `media_filter` function was:

```
function media_filter($text) {
  $text = preg_replace_callback(MEDIA_TOKEN_REGEX, 'media_token_to_markup', $text);
  return $text;
}

```

What is the current replacement for that function which I can use instead?

# Answer
> 4 votes
Prior to newer version of Media, `media_wysiwyg_filter` should be used instead which will perform media markup filter. This can be found in `modules/media_wysiwyg/includes/media_wysiwyg.filter.inc`.

The code is:

```
/**
 * Filter callback for media markup filter.
 */
function media_wysiwyg_filter($text) {
  $text = preg_replace_callback(MEDIA_WYSIWYG_TOKEN_REGEX, 'media_wysiwyg_token_to_markup', $text);
  return $text;
}

```

---
Tags: 7, media, upgrading
---


# Question
Title: Adding Data to a Variable in a Contributed Module
I'd like to add some data to a variable in a contributed module but I'm not sure how to do that with a custom module.

**The Question:**

The module I need to 'hack' is the Drupal Commerce PayPal WPP Module. I talked with PayPal and they said specifically I'd need to hack this file: 'commerce\_paypal\_wpp.module'. They said on line 365 if I added more data to the 'CUSTOM' variable (see below) it would pass that on to PayPal. Sweet! But how can I do that?

**My Proposed Solution**

I'm thinking I will create my variables to add to CUSTOM, like so (this is how I'd normally do it in PHP of course:

```
$fname = 'examplename';
$lname = 'examplelastname';
$arr = array($fname, $lname);
$allthedata = implode('+', $arr);
CUSTOM = $allthedata

```

It's that last line I don't know how to add properly! This, because 'CUSTOM' is already defined in the contributed module (see below).

**The Function I Need to Edit:**

The function in question in the contributed module is:

```
function commerce_paypal_wpp_submit_form_submit($payment_method,
$pane_form, $pane_values, $order, $charge) {

```

**And the relevant code with 'CUSTOM' \> the variable I want to change:**

```
// Add additional transaction invormation to the request array.
  $nvp += array(
    // Order Information; we append the timestamp to the order number to
allow
    // for multiple transactions against the same order.
    'INVNUM' => substr($order->order_number, 0, 127) . '-' . REQUEST_TIME,
    'CUSTOM' => substr(t('Order @number', array('@number' => $order-
>order_number)), 0, 256),
    'DESC' => substr(implode(', ', $description), 0, 127),

    // Customer Information
    'EMAIL' => substr($order->mail, 0, 127),
    'IPADDRESS' => substr($ip_address, 0, 15),
    'FIRSTNAME' => substr($billing_address['first_name'], 0, 25),
    'LASTNAME' => substr($billing_address['last_name'], 0, 25),
    'STREET' => substr($billing_address['thoroughfare'], 0, 100),
    'STREET2' => substr($billing_address['premise'], 0, 100),
    'CITY' => substr($billing_address['locality'], 0, 40),
    'STATE' => substr($billing_address['administrative_area'], 0, 40),
    'COUNTRYCODE' => $billing_address['country'],
    'ZIP' => substr($billing_address['postal_code'], 0, 20),
  );
}

```

# Answer
> 4 votes
You will not need to 'hack' this module, you can use a legitimate hook to modify the $nvp array, hook\_commerce\_paypal\_api\_request\_alter

At line 382 of the commerce\_paypal\_wpp.module, right after the part you mention, the whole array is passed to the commerce\_paypal\_api\_request where the mentioned hook is called early on, to allow modifications from other modules.

Following your example code, your hook implementation would look like this:

```
function yourmodule_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method) {
  ...
  $fname = 'examplename';
  $lname = 'examplelastname';
  $arr = array($fname, $lname);
  $allthedata = implode('+', $arr);
  $nvp['CUSTOM'] = $allthedata;
  ...
}

```

Hope this helps!

---
Tags: commerce
---


title: ckeditor issue while ajax submit

text:
# Question
Title: ckeditor issue while ajax submit
i m using ckeditor in a form that submits through ajax. when the submit is clicked and the submission is in progress my ckeditor converts into a plain text editor and all the controls are gone, as soon as the submit is complete, the controls are back, it looks ugly. Any solution?

# Answer
though the solution looks temporary but i see no bugs in it. The solution is to comment the line:

```
CKEDITOR.instances[textarea_id].destroy(true);

```

under ckeditor.utils.js

More better option would be to put a condition to skip the destruction of ckeditor instance
> 1 votes

# Answer
If you are deploying CKEditor via the new editor module (not via ckeditor as in the original question) and experience this issue, then it is due to Drupal issue #2691101. See there for a patch that solves it.
> 0 votes

---
Tags: ajax, wysiwyg
---


# Question
Title: How to enable drag and drop picture upload into CKEditor?
I would like to include the functionality of drag & drop image uploading in CKEditor of my Drupal webpage.

I have been looking for information about that but I can't find anything useful, have you ever done it? I hope you can help me.

# Answer
> 1 votes
Most drag&drop upload solutions are meant for image / file upload fields, but there is one more that integrates with CKEditor: the media module. According to its project page:

> Features: \[…\] Drag and drop upload (requires the Plupload module).

Choose the 7.x-2.x branch, it reportedly has better drag&drop image upload capabilities. Integration of media with CKEditor happens via the wysiwyg module, so if you deploy CKEditor instead via the ckeditor or editor modules, it may not work even if overriding dependencies, because these integrations have slightly differing APIs to talk to CKEditor.

# Answer
> 0 votes
The dragndrop\_uploads module is made exactly for your purpose. Despite the name, it's not a generic file upload module but made for image uploading into rich text editors. From the project page:

> The Drag'n'Drop Uploads module adds the ability to drag an image from your local filesystem, drop it onto a node body textarea and have the file automatically uploaded and referenced in your node. \[…\] \[It provides\] Support for the WYSIWYG module.

Note that "Support for the WYSIWYG module" means that drag&drop upload will work if you install CKEditor via the wysiwyg module, but *probably* not when you install it via the ckeditor or (the new favourite) the editor module. They all have slightly differing APIs.

---
Tags: wysiwyg, media
---


# Question
Title: Is it possible to turn off the auto-pathing for the Pathauto module?
I want to avoid the Pathauto module automatically creates node path aliases.

Is there a way to disable it?
I could want to enable it later, so I don't want the module cannot anymore automatically create path aliases.

# Answer
I don't know if this is possible without implement the `hook_form_alter()` function but you can use a different approach to solve the issue.

You can use a custom field instead that the title of the node. Set the field as "Required" and in `/admin/config/search/path/patterns`set the pattern of the node with the token of the field instead that the title (ie: \[node:field-seotitle\] ).

In other words:

* Add a field in your content type, for example: seotitle;
* Set the field as Required;
* Go in `/admin/config/search/path/patterns`;
* Set the pattern of the your content type where you have add the field with the token of the seotitle field (ie: your-content-type/\[node:field\_seotitle\]);

In this way you can choose a title for the path alias and save the node only until you have a seo-title;

I hope I explained myself.
> 4 votes

---
Tags: path-aliases
---


# Question
Title: How to get achievements notification popup for Ajax Callbacks?
I'm using the Achievements module to award the badges to users on certain actions.

In the following example user will get badges after posting 5 and 10 comments.

```
function MYMODULE_comment_insert($comment) {
  $current_count = achievements_storage_get('comment-count', $comment->uid) + 1;
  achievements_storage_set('comment-count', $current_count, $comment->uid);

  foreach (array(5,10) as $count) {
    if ($current_count == $count) {
      achievements_unlocked('comment-count-' . $count, $comment->uid);
    }
  }
}

```

The above code is working, user is able to achieve badge after posting 5 comments but since the comment form is being submitted through AJAX, the rewarded achievements notification popup is not being shown until page refresh.

So how can I show achievement notification popup for Ajax callbacks? Any suggestions?

# Answer
Here is another try at this (various assumptions follow):

* The whole thing should run through the Wall module's code, since this is the base for any other interaction happening.
* By means of the Form API and AJAX callbacks, there is a possible entry point. This is to wrap the submit callback for the \_drupal\_wall\_comment\_post\_form into another callback that will make sure the Achievements' related elements are updated.
* The steps in this process would be:

1. Use hook\_form\_alter to modify `_drupal_wall_comment_post_form`
    2. Modify `_drupal_wall_comment_post_form` by hijacking the ajax callback for the wall comment submissions: `$form['drupal_wall_submit']['#ajax']['callback'] =>_your_custom_wall_ajax_callback`
    3. Wrap the original callback in your ajax callback and extend it to trigger the Achievements popup functionality using the Ajax framework commands family:

    ```
    function _your_custom_wall_ajax_callback($form, $form_state) {
      $wall_wrapper = $form['drupal_wall_submit']['#ajax']['wrapper'];
      $wall_content = _drupal_wall_comment_ajax_form_post($form, $form_state);
      $commands = array();
      $commands[] = ajax_command_replace($wall_wrapper, $wall_content);

      // This is where you can write ajax commands to trigger Achievements functionality
      $commands[] = ajax_command_*();

      return array('#type' => 'ajax', '#commands' => $commands);
    }

    ```

Hope this brings you a step further!
> 1 votes

# Answer
You could try using Rules to add a rule for when a user post a comment and then do your thing

After creating the rule you can set conditions and actions, so you can check for the comment count and then act accordingly
> -1 votes

---
Tags: 7, ajax
---


# Question
Title: Crypt::hmacBase64() versus CsrfTokenGenerator::get() and CsrfTokenGenerator::validate()
In a module I am writing, I need to add a hidden field in the registration form, similarly to what the Honeypot module does.

```
$form['honeypot_time'] = [
  '#type' => 'hidden',
  '#title' => t('Timestamp'),
  '#default_value' => mymodule_get_signed_timestamp(time()),
  '#element_validate' => ['mymodule_signed_timestamp_validate'],
  '#cache' => [
    'max-age' => 0,
  ],
];

```

`mymodule_get_signed_timestamp()` concatenates the timestamp with a value used to avoid the timestamp is arbitrary changed. It could be computed in one of two ways:

1. Using `Crypt::hmacBase64()`
2. Using the csrf\_token service, which by default provides `CsrfTokenGenerator::get()` and `CsrfTokenGenerator::validate()`

The choose is then between one of the following snippets.

```
use \Drupal\Component\Utility;

$token = Crypt::hmacBase64($value, \Drupal::service('private_key')->get());

```

```
use \Drupal\Core\Access;

$token = \Drupal::csrfToken()->get($value);

```

The difference is apparently just that the csrf\_token service's methods use, as part of the key passed to `Crypt::hmacBase64()`, also the session's data and the hash salt set in the settings.php file.

Considering that, in most of the cases, I would be altering a form submitted from anonymous users who tries to register an account (but I cannot exclude I could be adding that form element to forms submitted from registered users), should I use the first method or the second one?

# Answer
> 0 votes
I made a quick test using the following code.

```
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Site\Settings;
use Drupal\Core\Access\CsrfToken;
use Drupal\Component\Utility\Crypt;

$autoloader = require_once 'autoload.php';

/**
 * Global flag to identify update.php and authorize.php runs.
 *
 * Identifies update.php and authorize.php runs, avoiding unwanted operations
 * such as css/js preprocessing and translation, and solves some theming issues.
 * The flag is checked in other places in Drupal code (not just authorize.php).
 */
const MAINTENANCE_MODE = 'update';

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->prepareLegacyRequest($request);
}
catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');

drupal_maintenance_theme();

$csrf_token = \Drupal::csrfToken();

$content[] = [
  '#markup' => t('First method: %token.<br />', ['%token' => Crypt::hmacBase64(123456, \Drupal::service('private_key')->get())]),
  '#cache' => ['max-age' => 0],
];
$content[] = [
  '#markup' => t('Second method: %token.<br />', ['%token' => $csrf_token->get(123456)]),
  '#cache' => ['max-age' => 0],
];

$renderer = \Drupal::service('bare_html_page_renderer');
$response = $renderer->renderBarePage($content, 'Test results', 'maintenance_page', array(
  '#show_messages' => FALSE,
));

$response->setStatusCode(400);
$response->send();

```

I then opened three different Firefox windows pointing them at the test script I wrote. This is what I got:

### First window

> First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
> Second method: OndzLnnASZLsuzABJltD\_HwK8dr48fEW\_hdWG9Lu02I.

### Second window

> First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
> Second method: J6oHkKdXeL9RUKHX4B1Sn418Yh8XD0tJbRrs459BI7A.

### Third window

> First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
> Second method: TYvxZiF7xS6hD2nn8pfHu0GR9OPw0X8xT1HfVDNWkXc.

With the second method, different users are going to get different values, even in the case the input value is the same.
I would say that using the csrf\_token service is preferable, in my case.

---
Tags: 8
---


# Question
Title: Created a sitemap using the modules views and views data
I just created a sitemap using the modules views and views data export. How do I add tag in the header.

thank you

# Answer
You'll need to edit the `views-data-export-xml-header.tpl.php` that corresponds to the view your wanting to edit. To find this out, click on Advanced, Theme, and then Information. You're looking for a line like this:

> Alternative style: views-data-export-xml-header.tpl.php, views-data-export-xml-header--test.tpl.php, views-data-export-xml-header--views-data-export.tpl.php, views-data-export-xml-header--test--views-data-export.tpl.php, views-data-export-xml-header--default.tpl.php, views-data-export-xml-header--default.tpl.php, views-data-export-xml-header--views-data-export-1.tpl.php, views-data-export-xml-header--test--views-data-export-1.tpl.php

Pick a filename and make the changes. **Note that if you're looking to wrap the results in additional tags, you'll need to override both the header and the footer files.**

You'd change:

```
// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>

```

To also include any other information:

```
// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>
<header-data>
</header-data>

```
> 1 votes

---
Tags: views
---


# Question
Title: How to have new fields show with default content on new items?
For example:

I created a content type with 2 fields, the default values are:

```
Field 1 = A
Field 2 = B

```

When creating BRAND new content items, the fields show up on display with populated default data:

```
A
B

```

But when editing content that was created BEFORE creating the fields it doesn't work.

Is it normal that the default fields will only work on NEW content items?

I want to be able to add fields to items

# Answer
> Is it normal that the default fields will only work on NEW content items?

Yes, that is normal.

The way I work around that to update the OLD fields:

1. Go to the database and export the field table.

* For format: select **CSV** (do not select "CSV for MS Excel")
2. Open the .csv file in Excel and make changes to the values.

* To replicate a cel fast in excel, highlight 1 cel and move mouse to the right bottom corner of the cel (cursor will change to a **+**), then hold down left click and scroll down.
3. Import back to the DB and check-mark "replace table data with file".
4. In Drupal, clear/flush the caches to see changes.
> 1 votes

---
Tags: entities
---


title: How to theme title field

text:
# Question
Title: How to theme title field
Normally when I theme a field, I use a template suggestion in format `field--fieldname--contenttype`. However, it doesn't seem to be possible to do this with the node title. I've tried both of the following template suggestions:

```
field--title--contenttype.tpl.php
field--field-title--contenttype.tpl.php

```

Neither of them work (I've cleared caches). The title isn't technically a field, since it's more like a property on the node object, so that may be the problem?

Is there any way to theme the title field? It feels like I'm missing something simple.

N.b. I'm using panels and have dropped the node title pane into the panel but need to theme it differently.

# Answer
You could use the Title module to convert your title to a proper field. Following that, your template file should work.
> 3 votes

# Answer
Why not just edit the css file? #content h1 { color: blue; } Something like this. Node title is wrapped in content div and it is or You may check your page.tpl.php
> 0 votes

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


# Question
Title: How to display a block if a Boolean on/off checkbox is checked?
I will eventually install Panels to accomplish this. But I can't at this time. I want to allow an editor to display a right sidebar menu on any page when they want by checking a Single on/off checkbox . I added a CCK field to the Page type - Boolean -Single on/off checkbox. I am using Drupal 7.43 on Centos 7 and php 5.4

There is a php block invoke inside another php that checks if a cck field is not null. The first php is looking at the Boolean field 'field\_hide\_sidebar\_menu' to see if it is null or not checked. If it is null it will display the block. This is not working. I have used 'if!empty' before to check if an image field is null and it works. Now I want it to check if the Boolean is checked or not checked so do I need to write this in a different way to check if the Boolean value is on or off - equal to 1 or equal to 0. Here is my code:

```
<?php if (!empty($entity['field_hide_sidebar_menu'])): ?> <div id="myclass">
<h2>Menu</h2> <?php $block = module_invoke('views', 'block_view',
'menu_sidebar-block_1'); print render($block['content']);?></div><?php
 endif; ?>

```

# Answer
> 0 votes
Generally, if you're wanting to enable or disable a block based on some parameters (and assuming this block is defined within a module of your writing), you'd use `hook_block_list_alter()`, test for your condition, and then either display or hide your block.

You can see how this works by look at the block module's implementation of it's own hook, `block_block_list_alter()`.

For instance, if you wanted to hide something based on the current node:

```
MYMODULE_block_list_alter(&$blocks) {
    $node = menu_get_object();
    $my_hiding_condition = isset($node->somefield[LANGUAGE_NONE][0]['value'])
      && $node->somefield[LANGUAGE_NONE][0]['value'] == TRUE;
    if (isset($blocks['my_block_id']) && $my_hiding_condition == TRUE) {
        // Hide the block.
        unset($blocks['my_block_id']);
    }
}

```

# Answer
> 0 votes
A good hook for this kind of thing is hook\_page\_alter

function hook\_page\_alter

> 7 system.api.php hook\_page\_alter(&$page)
>
> Perform alterations before a page is rendered.
>
> Use this hook when you want to remove or alter elements at the page level, or add elements at the page level that depend on an other module's elements (this hook runs after hook\_page\_build().
>
> If you are making changes to entities such as forms, menus, or user profiles, use those objects' native alter hooks instead (hook\_form\_alter(), for example).
>
> The $page array contains top level elements for each block region:
>
> $page\['page\_top'\]
>
> $page\['header'\]
>
> $page\['sidebar\_first'\]
>
> $page\['content'\]
>
> $page\['sidebar\_second'\]
>
> $page\['page\_bottom'\]

You can use menu\_get\_object to populate a variable named $node, test it for null, then node type, then your boolean value, and if satisfied you can render your block into the `$page['sidebar_second']` variable on the page.

# Answer
> 0 votes
You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the value of your Single on/off checkbox***".

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

---
Tags: 7, theming, blocks
---


# Question
Title: Using taxonomies with Field Collection in Drupal 7
How do you create a taxonomy listing when the field is being used in a field\_collection field type?

I'm working on modifying the Article content type for a newspaper website; specifically, I've added two field collections: one is a byline, with two fields ("author" \[taxonomy\] and "position" \[text\]; e.g. "Ændrew Rininsland, Production Editor") and another is an image, with three fields plus the image ("caption" \[text\], "author" \[taxonomy\], "organization" \[text\]).
Both of these are set to have unlimited values, such that each story can have multiple bylines and multiple photos, each with its own caption and photo credit.

What I'm wanting to do now is use the "author" taxonomy term to create a listing of each story each author/photographer has contributed to. Simply going to the term's taxonomy page doesn't work; that only lists nodes with attached taxonomy terms, not fields (such as a field\_collection). See this issue.

# Answer
> 1 votes
I finally got around to solving this issue, and managed not one but TWO different ways of solving it.

The hard way (writing a module): http://drupal.org/node/1291246#comment-5811912

The easy way (creating a view): http://drupal.org/node/1291246#comment-5812572

Quoting the latter:

> Using the example above (unlimited value field collection named "field\_bylines" containing a taxonomy field "field\_author" and text field "field\_position"), you can accomplish pretty much the exact same thing by creating the following view:
>
> 1. Create a view, call it whatever you want. Make path something like "author/%"
> 2. Click Advanced, Add a Relationship. Choose your field collection; in this case, "Content: Bylines"
> 3. Add a Contextual Filter. This will be the taxonomy field (I.e., "field\_author"), should appear named something like: "(field collection item from field\_bylines) Field collection item: Author". Tell it not to display anything when filter value is not in the URL.
>
> Tah-dah. Should work. If you want your field collection listed in the results instead of the default user creating the content:
>
> 1. Under Format, click "Content". Change to "Fields".
> 2. Under Fields, Click Add and select "Content: Bylines". Change formatter to "Fields Only" and uncheck "Create a label". (Last two are my preference to tidy UI up)
>
> Note that you'll have to supply the author's term id to the view instead of the term name (I've never figured how to supply a term name as an argument as opposed to a tid...).

Hope this saves somebody the frustration it caused me. Field Collections really need better docs...

# Answer
> 1 votes
Ultimately, I'd build a view that looks at the taxonomy term and then uses a node reference for other information supplied. The Second post in your issue points to another issue that contains a lot info about views integration and node references. If you can't find a solution there, I'd add your needs into the mix and follow that discussion.

# Answer
> 0 votes
Below are the steps to use your field collection taxonomy field into exposed filter.

step1 - create a content view.
step2 - add your field collection taxonomy field into relation.
step3 - also add same field into filter criteria and set it as exposed filter.

now your taxonomy dropdown should be appear with working condition.

---
Tags: 7, entities
---


title: Allowing downpayment

text:
# Question
Title: Allowing downpayment
Is the a way to allow downpayment for customer-preoders. I can create a content type that allows customers to place orders(pre-order) but I wish they could commit a certain fee, like 30% of the original price. Is there a way to achieve this?

# Answer
If you use commerce, you and try and incorporate modules like these into your workflow: commerce\_payment\_split commerce\_partial\_payment commerce\_installments

For ubercart, there is: uc\_partialpayment

My advice will be to look at these modules and then decide if you need a customized module based on one of these.
> 0 votes

# Answer
There are plenty of modules are available for managing inventory and orders. Like Ubercart, Commerce.

But according to your requirement it seems that you want a partial payment system.

The default modules available in drupal community will not be able to provide you such kind of feature.

My Suggestion is to create it completely using your custom module and manage the complete order and partial payment process system.

Hope this will help you.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to create nodes from shell script at server?
I need to create nodes from shell script at my server (some server statistics).

As I know **drush** cannot add new node. (It was a discovery for me)

So I think make shell script which will create CSV file with node fields and make periodical import by **Feeds**.

Is there more smart solution?

# Answer
> 7 votes
If you are going to start scripting on the command line, you can always script a php script and run it via drush. That way, you have access to your Drupal system and data. For example, if you place the following code in a file, e.g. script\_create\_node.php:

```
<?php

// Expect title as $args[1] and body as $args[2]
if( !isset($args[1]) || trim($args[1]) == '' || !isset($args[2]) || trim($args[2]) == '') {
  print "Expecting two arguments on the command line, title and body, for the new article\n";
  exit;
}

$node = new stdClass();  // Create a new node object
$node->type = 'article';  // Content type
$node->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
node_object_prepare($node);  //Set some default values

$node->title = $args[1];
$node->body[$node->language][0]['value'] = $args[2];

$node->status = 1;   // (1 or 0): published or unpublished
$node->promote = 0;  // (1 or 0): promoted to front page or not
$node->sticky = 0;  // (1 or 0): sticky at top of lists or not
$node->comment = 1;  // 2 = comments open, 1 = comments closed, 0 = comments hidden
// Add author of the node
$node->uid = 1;

// Save the node
node_save($node);

```

you can always call this on the terminal like this:

```
drush scr script_create_node.php "Article Title" "Article Body"

```

You can extend such a script to include the logic you would use in your shell script, but instead of writing to a CSV file, you can write directly to the database. It's a great advantage having both PHP-CLI and a bootstrapped Drupal available at the same time.

Hope this helps some!

P.S: Lots of pages out there answering the question "programmatically creating nodes", one random pick would be http://www.group42.ca/creating\_and\_updating\_nodes\_programmatically\_in\_drupal\_7

# Answer
> 1 votes
There are a lot of right answers here; using feeds would work fine. You might also be interested to try Drush Entity Commands.

# Answer
> 0 votes
Don't forget `drush genc` if you have the `devel` module installed. Old school but effective, creates fully populated nodes with randomly generated images etc. (You can also use it to delete nodes as well: `drush genc --kill --types=NODE_TYPE 0 0`)

```
> drush genc --help
Create content.

Arguments:
 number_nodes                              Number of nodes to generate.
 maximum_comments                          Maximum number of comments to generate.

Options:
 --feedback                                An integer representing interval for insertion rate logging. Defaults to 1000
 --kill                                    Delete all content before generating new content.
 --languages                               A comma-separated list of language codes
 --skip-fields                             A comma delimited list of fields to omit when generating random values
 --types                                   A comma delimited list of content types to create. Defaults to page,article.

```

---
Tags: drush
---


# Question
Title: How to increase password length while creating account on a drupal website?
I'm using Drupal 7, is there any configuration on drupal to make users choose passwords with more than `10` characters (for example) when they're creating accounts ? For now, any user can choose username, and a password can contain only one letter and it's not safe.

Thank you.

# Answer
> 2 votes
Sounds as if you need the Password Policy module.

From the project page:

> This module provides a way to enforce restrictions on user passwords by defining password policies.
> A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.

---
Tags: 7
---


# Question
Title: How to check the remaining capacity for an event when using the Registration module?
I am trying to create a Rule (using the Rules module) that fires off an email when the capacity of registrations for an event get full. We have set this up using the Registration module.

I set this rule up like so:

* Event = Upon new registration.
* Condition: Data comparison - registration:count.
* Action = email author.

In the manage registrations tab the `registration-count` is always 1 for each user. So I wonder how I can check the capacity for the event to trigger the email.

I have tried to search for information and try many scenarios, however not finding one that works.

I would like some idea(s) or path to a solution I am not thinking of.

# Answer
The Rules module is a very flexible framework and it has a comprehensive api. While you may be able to accomplish your task using just the UI you may find it easier implement one or couple of hooks to alter your existing condition, or perhaps, add a new condition to be used. For example,

```
/**
 * Implementation of hook_rules_condition_info().
 * @ingroup rules
 */
function yourmodule_rules_condition_info() {
  return array(
    'yourmodule_condition_example' => array(
      'label' => t('Compare two users'),
      'arguments' => array(
        'user1' => array('type' => 'user', 'label' => t('First user to compare')),
        'user2' => array('type' => 'user', 'label' => t('Second user to compare'))
      ),
      'module' => 'user',
    ),
  );
}

```

If you decide to go this way, you may want to check https://drupal.org/node/298533
> 0 votes

# Answer
The Entity Registration module (not just *Registration* ...) is all about entities. So it should work together with the Rules module pretty well.

If you can't get it to work ysing that "`registration-count`", you might want to try adding the Entity Reference Count module. Some more details about this module (from its project page):

> This module provides an easy way for an entity to keep track of how many other entities are currently referencing it through Entity Reference fields attached to other entities.

Another approach is to use the Flag module, whereas each time somebody registers for the event, you flag the event. With an additional rule you then just check the number of times the event got flagged (should be equal to the event count).

**Note**: the video about Drupal 7 Entity Registration Module shows (around 4:55) the (mandatory) "Capacity"\* field also, which you might want to use to limit the maximuim number of registrants (use "0" for no limit).
> 0 votes

---
Tags: rules, entities
---


# Question
Title: "Create a new account for an anonymous order" Rule issue with required field
I am using Drupal Commerce. I have enabled the anonymous user to access checkout and place an order. There is this rule available in Drupal commerce("Create a new account for an anonymous order") that creates an account for user's who do not have an account and checkout anonymously.

**The Problem** is that there is an image field which is required in the user account form. So due this, it is having issue creating a new user, as I am not able to supply a value to it. I have set a default image, but its still having the same issue.

Anyone knows how to set this default image or make it non-required to add image while creating account through rules?

?

# Answer
Two options:

1. Make the field not required at the field level but then use a Form alter hook to make it required when presenting the form.
2. Make the logo point to the default image by setting the data value to `public://your-file-here.png` inside of the rule.
> 0 votes

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


# Question
Title: How to generate the function stack trace of the last request made?
Is there a module that can essentially show you the function stack trace of the last request made?

Say I have a form that I submit. After the page loads with the result from the request, I would like to see a list of all the functions that were called, start to finish, that resulted in the currently loaded page.

# Answer
> 4 votes
A function trace will only show you the function calls that lead directly to that piece of code.

PHP provides the functions `debug_print_backtrace()` for that, which is however not very readable but it will result a huge amount of text. devel.module provides a `ddebug_backtrace()`function, which us much easier to read.

To see all function calls of a single page, you need to install a profiler like XhProf.

# Answer
> 2 votes
### XDebug

You can use PHP XDebug extension with the following options:

* start/stop by `xdebug_start_trace()`/`xdebug_stop_trace()` at the specific places (e.g. before form submit),
* set `xdebug.auto_trace=1` in `php.ini` for full trace,
* use `xdebug_print_function_stack()` to display your current function stack,
* use `xdebug.remote_enable=1` in `php.ini` to use debugger directly from IDE for step-by-step debugging.

Check: XDebug Docs.

See my suggested `xdebug.ini` config file for PHP.

### DTrace

If your system supports DTrace (e.g. OS X) and your PHP has been configured with DTrace static probes (`php -i | grep dtrace`), the following command will trace all your function calls:

```
sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

```

This should work in Apache, if not, you may re-run your CMS by using builtin PHP server, e.g.:

```
php -S localhost:8080

```

then access your site at http://localhost:8080/, so when you submit the form - you should see trace output containing all functions that were called as result of loaded page.

For more scripts, check my `dtruss-lamp` repository.

---
Tags: debugging
---


# Question
Title: How to trace down to find where a field has been removed/hidden of a particular node
I am using a purchased theme provided by 3rd party (it is actually a custom Drupal build comes with their modules and theme). My problem is that image fields are hidden some where in the module(s) provided by this theme.

I am sure that the `apartment.field_image` is not removed in the template (neither by using any `hidden()` function nor by non printing the `$content['field_image']`. I came to this conclusion by observing the `$content` using Devel module as well as by using standard `dpm()` function. That field is just not there (node content) at all.

I have also made sure its not hidden in the display settings of this content type its "image".

I have checked rest of the code by searching for preprocess, `field_image` and image to see if they are manipulating it anywhere. I found many processor functions which were manipulating something else like adding css etc., but but I dint find any traces where they are hiding/unsetting/removing the field.

Please guide me how can I trace it. My mind is just blowing off. Thought I would get good sleep after a week but looks not the case.

# Answer
some things to look at: make sure under display, that the type of display is set correctly (full content, teaser, default, etc). Check if field permissions or similar is installed and that the permissions for that field are set correctly. Check for any rules or actions that could be causing it to be removed.

another - is it in a field collection, display settings for those are shown under /admin/structures/field collections not under the content type
> 0 votes

# Answer
You may use DevTools in Chrome browser to find out how and from where the element has been hidden of a particular node, by setting the breakpoint on that element on subtree & attributes modifications or node removal in contextual menu as shown below:

Alternatively you may try Visual Event or Visual Event 2 which can show you debugging information about events that have been attached to DOM elements. See: How to find event listeners on a DOM node?
> 0 votes

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


# Question
Title: How to display a message even when user is logged out?
I'm using Drupal 7, i want to display a message `drupal_set_message`, when i click on a button for example.

When i'm logged it works well, but for this same button (or page) if i'm not logged in, it doesn't display any message.

This is my case : i've created a mobile application that used a backoffice. this backoffice is built using drupal. i've created a page "reset password" user can click on "reset password" from the mobile app, an email sent with a link to my custom page : reset\_pwd

this page contains inputs to reset new password :

```
$items['reset_psw'] = array(
'title' => '',
    'description' => '',
    'access arguments' => array('administer reset_psw'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('reset_mdp_formulaire'),
);
return $items;

```

the form to reset password :

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

$form = array();

$form['confirm_pass'] = array(
    '#type' => 'password_confirm',
);

$form['valider'] = array(
    '#value' => t('valider'),
    '#type' => 'submit',
);
return $form;
 }

```

the function submit :

```
function reset_mdp_formulaire_submit ($form, &$form_state){
$new_pass = $form_state['values']['confirm_pass'];
dsm("error");
if(strlen($new_pass) < 8){

    drupal_set_message(t('Password must be 8 characters at least.'), 'error'); <== not shown when logged out
    return;
}
 }

```

Just want to check if new password is less than 8 characters, and display error message

Thank you all.

# Answer
> 1 votes
Try removing the return statement at the end of your submit or even replacing it with a drupal\_goto('reset\_psw').

There are lots of similar questions on google and S.O., you could have a look.

UPDATE

You should use the validate handler for such a case, this simple example should get you going https://www.drupal.org/node/717740

---
Tags: 7
---


# Question
Title: Solving "MySQL server has gone away", mysql error 2006
I have a site at hostgator, using their "Business account". It's cheap, and comes with a private SSL cert. HOWEVER, their MySQL settings are such that any db connection goes stale fairly quickly, and then the hostgator staff try to convince you to use a VPS or dedicated server at multiple times the expense.

I'm creating and deploying WebAPIs, which can have a 'conversation' which exceeds 60 seconds. When this occurs, the db connection handle is stale, causing any db operations after my timeout to fail.

I'm in the process of implementing the following solution, but am curious if anyone else has solved this issue (where they can not modify their my.ini or my.cnf to give MySQL more resources) in a similar or completely different manner.

last part of a hook\_update:

```
$ret = db_query( "UPDATE {my_table} set field1 = '%s', field2 = %d ... WHERE vid - %d", $node->field1, $node->field2, ... $node->vid );
if (!$ret) {
       // get private storage directory for this node:
       $cexStorage    = _cex_front_getCexStore();
       $nodeFilesPath = DRUPALROOT.'/'.$cexStorage.'/'.$node->storeDir;
       $fname         = $nodeFilesPath.'/recover.node';
       $readyToWrite  = serialize( $node );
       file_put_contents( $fname, $readyToWrite );
       if (file_exists( $fname )) {
         _dbgReport( 'seems to have worked!' );
       }
    }

```

Then this is called in my hook\_form, right after I determine that node-\>nid is valid:

```
function _cex_front_recover_node( &$node ) {
  if (!isset($node->storeDir)) {
     _dbgReport( '**************************** _cex_front_recover_node: no storeDir!!!' );
     return;
  }

  // get private storage directory for this node:
  $cexStorage    = _cex_front_getCexStore();
  $nodeFilesPath = DRUPALROOT.'/'.$cexStorage.'/'.$node->storeDir;
  $fname         = $nodeFilesPath.'/recover.node';
  if (file_exists( $fname )) {
    $recovered = file_get_contents( $fname );
    if ($recovered) {
      // no longer needed:
      unlink( $fname );
      $recoveredNode = unserialize( $recovered );
      // restore the key values I need to proceed with this node:
      $node->stage = $recoveredNode->stage;
      $node->rnid  = $recoveredNode->rnid;
      $node->iris  = $recoveredNode->iris;
      cex_front_update( $node );
    }
    else {
      _dbgReport( '********* failed to read "'.$fname.'"' );
    }
  }
}

```

I'll be pairing the logic down to only store the key fields I need, but this works! Sure beats upgrading my server at 3x the expense. Anyone else doing something like this?

# Answer
I had a client on a hosting company that refused to increase the value of max\_allowed\_packet (2MB), regularly leading to the inability to add info-items to the cache. I solved that by adding compression. See Compress cache data before storing it in the database.

In your case, reducing the resource usage may be done with spreading it out over batch operations.
> 5 votes

# Answer
We had a similar issue where we are using two databases. We would do some work on the first database, then run very long-running processes against the second database, then when we tried to use the first database again, the connection had died.

We resolved this using the mysqli.reconnect setting in php.ini - if you don't have access to that, you can add it to your settings.php. There are some caveats with this setting, such as transactions being partially completed, but these will probably not be relevant to your setup.
> 4 votes

# Answer
This error is usually related to parsing of large amount of data, so database may fail to respond (timeout) as it can't handle such sizes due the given limits, therefore the server timing out and closing the connection.

To fix it, you need to increase further up the value of `max_allowed_packet` in your `my.cnf` (e.g. `~/.my.cnf`) under `[mysqld]` section, e.g.

```
[mysqld]
max_allowed_packet=256M

```

Try with `256M`, if won't help, try increasing further more (e.g. `1G`).

In your case, I think `max_allowed_packet` should be under `[mysqld]` section specifically, not under `[mysqld_safe]`, so settings are applied to the right component.

See: B.5.2.9 MySQL server has gone away for more detailed information.

Another thing is that in this particular case it happens in shutdown function (which is after Drupal finished the processing of the site), therefore it could be related to some cron or debugging tasks.

---

If your hosting provider refuses increasing `max_allowed_packet`, you should consider changing to different hosting provider which supports Drupal system requirements.

---

Related:
> 1 votes

---
Tags: database
---


# Question
Title: Using Ctools, how do I render a managed_file from system form?
I'm adding some fields to Drupals site-information form. Textfields and managed\_file fields. Images are uploaded there and not in my panel panes edit form.

Now I want to make the additional fields I've added, or just the whole form be rendered in a custom panel content\_type. I have no issue getting the textfields themselves using

```
$block->content .= filter_xss_admin(variable_get('phonenumber', ''));

```

however I also need to render my managed\_file. How would I go about doing so?

# Answer
> 0 votes
Okay, it's not my day today :D

Here's how to do what you were asking:

```
// Load the managed file. You need this so you can get the URI.
$file = file_load(YOUR_FILE_ID);
// Generate the output.
$output = theme('image', array(
  'alt' => t('Your image alt title'),
  'title' => t('Your image human title'),
  'attributes' => array('src' => $file->uri),
));

```

---
Tags: 7, panels, chaos-tool-suite
---


# Question
Title: Error entries in Watchdog duplicated dozen and hundreds of times
I have seen that the table watchdog in my MySQL database is growing enormously, and after TRUNCATE, I see that for each visit to a single page, it generates hundreds of inserts, and when seeing them, they appear to repeat dozen and dozen of times. How can I trace where the error is, because I would bet this is a misconfiguration or something. I am worry that Drupal is making thousand of redirections, I have no other explanation, the pages load fast but the machine has a lot of RAM and hardware, so maybe I am loosing performance somewhere.

# Answer
The best is to check what these entries are and try to fix them, e.g.:

* when the warning/error comes from contrib module, consider searching for this specific error and find out what's the solution (sometimes it may be misconfigured module),
* when warnings comes from your custom modules or themes, consider fixing it manually.

If you think you cannot fix the source of the issues, you should introduce caching mechanism to your site such as:

* Redis/Memcached which will limit enormous number of inserts into cache tables.
* Varnish to cache the front end pages.

or limit the entries by:

See also: How do you improve Drupal performance?
> 0 votes

---
Tags: 7, performance, log-messages
---