Drupal 7 module hook_preprocess_page &$vars In my module I have verified this function is being called, but when I try to edit page--golfguide--alias.tpl.php it doesn't have the variables available.

In module:

function dc_branding_preprocess_page(&$vars)
{
    $vars['branded_header'] = dc_branding_header_contents();
    $vars['branded_footer'] = dc_branding_footer_contents();
}

In template.php for theme:

function golfguide_preprocess_page(&$vars, $hook)
{
    global $user, $is_mobile;
    if (isset($vars['node']))
    {
      // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->type;

      // If the node id is "33" the template suggestion will be "page--33.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->nid;
    }
    //Create page suggestion for first part of url-alias
    $url_alias = drupal_get_path_alias($_GET['q']);
    $parts = explode('/', $url_alias);
    $parts[0] = str_replace('-', '', $parts[0]);
    $vars['theme_hook_suggestions'][] = 'page__'.$parts[0].'__alias';

    if($is_mobile)
    {
        $vars['theme_hook_suggestions'][] = 'page__'.$parts[0].'__mobile';
    }
}

In page--golfguide--alias.tpl.php

<?php print render($page['branded_footer']); ?>

NOTHING outputs and the key branded_footer does not exist.

You are trying to render $page['branded_footer'], but the module preprocess function is setting $vars['branded_footer'], which would be accessible as $branded_footer in the template file.

$page['branded_footer'] would be set if the theme defines a branded_footer region. In that case, you should follow what How do I create custom regions in a theme? says.


Views Exposed filter text search for multiple value field I have 6 fields (in Profile2) I want to combine into an exposed "Global: Combine field filter":

Field 1 = text field with 1 value (text)
Field 2 = text field with 1 value (text)
Field 3 = text field with 1 value (text)
Field 4 = text field with 1 value (text)
Field 5 = long text field with 1 value (long text)
Field 6 = text field set to unlimited number of values (text)

That last one is the problem. I want the user to be able to add several distinct values in this field, and I want to be able to create a combined field text search that includes the text from all of these fields, including all the separate values in Field 6.

If I isolate Field 6 and give it it's own exposed filter search field, it works fine. But if I try to make it one of the combined fields (using the Global: Combine fields filter), searches don't see the various text values in Field 6.

[BTW, I'm using Better Exposed Filters, though I don't think they are in use for the Global: Combine fields filter.]

You will probably want to add a (7th) Text field filtering on the same data as Field 6 and group it with an OR to Field 6. Then, you can use Field 7 in the Global: Combine fields filter and not have it overwrite the use-supplied values in Field 6.


Drush - /usr/bin/drush: line 129: /usr/bin/php: Success When I run any drush command I am getting this line:

/usr/bin/drush: line 129: /usr/bin/php: Success

For example:

[root@061889 ~]# drush
/usr/bin/drush: line 129: /usr/bin/php: Success
[root@061889 ~]# drush cron
/usr/bin/drush: line 129: /usr/bin/php: Success
[root@061889 ~]# drush help
/usr/bin/drush: line 129: /usr/bin/php: Success

I've tried rebooting my VPS but am still getting the same issue. This has been discovered while trying to get past a "Attempting to re-run cron while it is already running" error, in case that has any relevance. But, you've guessed it...

[root@061889 ~]# drush vdel cron_semaphore
/usr/bin/drush: line 129: /usr/bin/php: Success

Any ideas?

just run

  $ /usr/bin/drush

if it runs it means that your symlink to the drush command is wrong


Admin menu disappearing I'm running Drupal 7.54 and for some strange reason my admin menu on top disappears. This happens sporadically, no telling what's going to happen next. I've done some searching and found

$conf['admin_menu_cache_client'] = FALSE;

I added this line of code to the settings.php file and that didn't help.

I was wondering if anyone else had experienced the same problem and tried any solutions.

below is the javascript error

GET https://www.nokidhungry.org/modules/comment/comment.css?otg3j2
smiah:18 Uncaught TypeError: Cannot read property 'prototype' of undefined
    at HTMLDocument.<anonymous> (js_lfuW81Xw_ijrPfg5E_XWjUDemAzqGwWRZunpwj_BL20.js:1032)
    at c (jquery.min.js:4)
    at Object.fireWith [as resolveWith] (jquery.min.js:4)
    at Function.ready (jquery.min.js:4)
    at HTMLDocument.q (jquery.min.js:4)
    at HTMLDocument.nrWrapper (smiah:18)
(anonymous) @ js_lfuW81Xw_ijrPfg5E_XWjUDemAzqGwWRZunpwj_BL20.js:1032
c @ jquery.min.js:4
fireWith @ jquery.min.js:4
ready @ jquery.min.js:4
q @ jquery.min.js:4
nrWrapper @ smiah:18

I think the error below is causing the issue and I don't know how to get rid of it.

Here's a checklist of things to look at:

Drupal simply concatenates files during aggregation. Malformed scripts may cause the entire thing to blow up. Disable aggregation first to see the code in plain so it's easier to debug.
Aggregation can also lead to some weird issues together with caching. Ensure that you've refreshed the cache for both Drupal, browser and any external file systems (i.e. S3) to ensure that you're working with updated code and content.
Malformed CSS, believe it or not, can also cause aggregation to blow up. Chrome does not show any error of this happening. However, Firefox prints a warning if it does. Debug in Firefox to see some errors not shown by Chrome.
If you're using S3 for storage, ensure that all of your resources are present. Sometimes, the file may not be accessible from S3, fail to upload to S3, or just be missing (i.e. deleted accidentally).
You already mentioned disabling admin menu caching. That has solved this problem for me in two projects.
Clear all caches (drush cc all). Always worked. :D


How do I truncate strings? For example, I need to truncate the following text.

  Drupal is free, flexible, robust and constantly being improved by hundreds of thousands of passionate people from all over the world. Join us!

I have used drupal_substr(), but the result may be "Drupal is free, flexi."
How can I avoid to truncate a word?

You need to use truncate_utf8() using $wordsafe = TRUE;

  $wordsafe Flag to truncate at last space within the upper limit. Defaults to FALSE.


Programmatically update an entity reference field I know I can update (or set a value for) an entity reference field in Drupal 7 with code similar to the following.

 $node['field_code_used_by'][LANGUAGE_NONE][0]['target_id'] = $id;

I want to programmatically set a value for my user entity reference field in Drupal 8.

I tried with $node->field_code_used_by->setValue(1); and $node->field_code_used_by->entity->value = 1; but neither of them worked.

How can I set the value for an entity reference field?

You need to use code similar to the following.

    $node = Node::load($nid);
    $node->field_code_used_by->target_id = $user_id;
    $node->save();

For a multiple-value field, to add the value to the end of the list, use the following code.

$node->field_code_used_by[] = ['target_id' => $user_id];

Another way is setting the entity property with the entity object, as in the following code.

    $node = Node::load($nid);
    $user = \Drupal\user\Entity\User::load(1);
    $node->field_code_used_by->entity = $user;
    $node->save();


Why doesn't a certain block appear on "view" pages of my site? After much searching online, I can't figure out why my "search" block is not showing up on every single page of my website. I went to the configure screen for the block and ticked the "All pages except those listed" radio button and didn't list any pages in the field below. So that should make the block appear on every page of my site, correct? That's not the case, however; there are a handful of pages, most of which are "views" (i.e., the page shows a series of tabs -- View, Edit, etc.) where the block simply doesn't show up. Am I doing something wrong?

I think you have got issue with the rendering of that particular region into the page.tpl.php, where this block doesn't show.

Follow this steps to identify the issue --

Find the machine name for the region where you are putting your block from the THEME.info file.
Open your all page*.tpl.php file in the theme one by one. May be your theme contain different page.tpl.php for different kind of content display. If it not done by you then this step can be hectic as sometimes we declare the custom page.tpl.php structure in template.php too. But initially you can check all the TPL files starting with page.
Check for the rendering of the content by searching the machine name which you have got in .info file for the region where you are placing the block. I think somewhere it's not rendered.
Render the region into the TPL file where it is not. Clear the cache & check you display.


How to allow a block on a page to load another block on same page in Drupal 7? This is what I am looking for: On a page that has a block, I want the ability of a link within that block to load another block on the same page. (Specific case: a static page has a Views block containing a grid of team members with a 'see more' link under their picture. I want that link to load the user profile as a block, but on the same page - presumably this should use ajax).

Any help on how to do this would be supremely appreciated. Thanks.

Can't post images on Drupal.stackexchange yet but here are two screenshots to illustrate what I am looking to do: http://goo.gl/WBgcR

As i understood from your problem, i think you can benefit from this lesson
Ajax node reader in drupal
http://www.youtube.com/watch?v=zyLmQtiSXgI

and there is a module called Ajax Blocks, can benefit u if u wnt to creat ur own module.

and as alternative solutions u can use
 http://drupal.org/project/colorbox_node
so the user profile loads in colorbox modal dialog


Show more fields under admin/people when i go to admin/people section. it is showing  me

username, roles, etc.

I want to show first_name, last_name as well.

is there is any way to do this

Thanks

Install the module Admin Views
An overview from the module page:

Replaces administrative overview/listing pages with actual views for superior usability.
Features

Filter all administrative views via AJAX.
Perform any kind of bulk/mass operations on items in administrative views.
Filter content by title, node type, author, published status, and/or vocabulary.
Filter comments by title, author, node title, or published status.
Filter users by name, ban/blocked status, or user roles.

Once installed this module will replace the main admin content page, and the admin user page with pre-made views. You can then customise these to suit your needs (adding or removing fields / filters).


How to load a view via ajax without breaking ajax functionality? What ist the correct way to load a View via Ajax and not breaking the view ajax functionality like the pager?

I tried it this way:

In a template:

<a href="/example-module/15?token=ugi2XH02Cumb3lsbSrOutwzRYSMXmn_bRKJI3FQ-hhk" class="btn use-ajax" role="button" rel="nofollow">
  {{- 'Load View' -}}
</a>

In the routing file:

example_module.example:
  path: '/example-module/{node_entity}'
defaults:
  _controller: '\Drupal\example_module\Controller\LoadViewController::render'
  _title: 'Load View'
options:
  parameters:
    node_entity:
      type: entity:node
requirements:
  _permission: 'access content'
  _csrf_token: 'TRUE'

In the Controller:

public function render(NodeInterface $node_entity, Request $request) {
  $node_id = $node_entity->id();
  if ($request->get(MainContentViewSubscriber::WRAPPER_FORMAT) == 'drupal_ajax') {
    $views_block = views_embed_view('load_view', 'block_1', $node_id);

    $response = new AjaxResponse();
    $selector = '#example-id';
    $replace = new ReplaceCommand($selector, \Drupal::service('renderer')->render($views_block));
    $response->addCommand($replace);
    return $response;
  }
  else {
    // For entities that don't have a canonical URL (like paragraphs),
    // redirect to the front page.
    $front = Url::fromUri('internal:/');
    $response = new RedirectResponse($front);
  }
  return $response;
}

This code works well. With two exceptions:

The view is not working with ajax (e.g. Pager). But the option "use AJAX" is checked in the UI
--- I also tried it with the Views::getView() method and add explicit the $view->setAjaxEnabled(TRUE) option. No success.
The Pager of the View has the URL of the controller in it, not the URL from the current rendered page.

So if you click on the Pager of the new loaded Views, the page reloads and show you on a white screen the Ajax command, but no specific error, not in the console and not in the logs.

Is this way not working or what I'm doing wrong?

After examining the ViewAjaxController.php ajaxView() function, I came up with the following solution, which seems functioning for me. I created an ajax endpoint which extends ViewAjaxController and sets the requested view and display in the Request object then calls the parent ajaxView() method.

1. Define the route

my_module.routing.yml

my_module.views_ajax:
  path: '/admin/views/{nojs}/{view_id}/{display_id}/{args}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleViewAjaxController::ajaxView'
  requirements:
    _permission: 'access content'

2. Create the controller

src/Controller/MyModuleViewAjaxController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\views\Controller\ViewAjaxController;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MyModuleViewAjaxController
 */
class MyModuleViewAjaxController extends ViewAjaxController {

  public function ajaxView(Request $request) {
    $view_name = $request->get('view_id');
    $display_id = $request->get('display_id');
    $dom_id = "{$view_name}__{$display_id}";

    $request->request->set('view_name', $view_name);
    $request->request->set('view_display_id', $display_id);
    $request->request->set('view_args', $request->get('args'));
    $request->request->set('view_dom_id', $dom_id);

    return parent::ajaxView($request);
  }

}

3. Create a wrapper
 to embed the view

The
 where you want to load a view via ajax has to have a specific css class in form of: .js-view-dom-id-{view_id}__{display_id}. Here replace the placeholders for view and display ids with the actual ones you want to embed.

4. Load the view via ajax link

Now you can load the view creating links like:

    This link will load the view {view_id} display {display_id} with the
    arguments {args}


Drush 5 & 8 side-by-side Is it possible have version 5 & 8 of Drush installed and to use a preferred version?

I am running an ubuntu server on which I have Drush5 installed. My attempts to remove is results in the following:

sudo apt-get autoremove drush -y
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 linux-image-extra-3.13.0-91-generic : Depends: linux-image-3.13.0-91-generic but it is not going to be installed
 linux-image-extra-3.13.0-95-generic : Depends: linux-image-3.13.0-95-generic but it is not going to be installed
 linux-image-generic : Depends: linux-image-3.13.0-95-generic but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

All attempts to deal with that issue have been unsuccessful.

So, I'm just wondering if both versions can be installed and used independently?

Yes.

alias drush5='~/drush5/drush'
alias drush6='~/drush6/vendor/bin/drush'
alias drush7='~/drush7/vendor/bin/drush'
alias drush8='~/drush8/vendor/bin/drush'

You will get help from Switching Drush Versions.


Confirmation email for newsletter signups drupal 7 Is it possible to send a confirmation email when someone signs up to my newsletter. When the user signs up an email should be sent to his mail conforming his subscripition and to await more info. Is this possible through the webform?

This is absolutely possible.

Go to admin/content/webform
Click Edit for the webform you want to modify.
Click on the Webform tab
Click on the E-mails sub-tab
Add a new one.

Once in there you can set all of the options you need to send an email to the person signing up.


Help with view styling - template/css/whatever Our client saw the schedule view of DrupalCon Denver's site and wants one of their conference schedule views to look like that:

Obviously we're styling things differently, but what they really want is the track icons to display in the exposed filter and alongside the individual sessions.

Individual Sessions
We have a content type called session, and a taxonomy called track. The taxonomy has an image field called track icon (field_track_icon), and there's a term reference field on the session that holds the selected track.

I managed to get the icons to display in the view with the sessions:

View setup -

Preview -

But I need to do some conditional processing - if the field "field_hide_track" on the individual session is true, then don't display track icons (or the value of field_hide_track, obviously.) We have a certain session type that needs to contain all of the choices from the taxonomy (i.e. be associated with all tracks) but do not want it to have a visual indicator. Right now, because they have all the choices, the view displays all of the icons from the taxonomy. It also displays the icon twice if there are multiple speakers, but I think that's because of the way we have things grouped. Basically we want the icon to display before the session number/title line for all sessions that don't have field_hide_track checked.

I've tried custom templates (views-view-fields--at-a-glance-test--page.tpl.php and views-view-field--at-a-glance-test--page.tpl.php, where the view's machine name is at_a_glance_test), but can't figure out how to get the information I need to do the conditional processing. Can someone point me in the right direction?

Exposed filter
I have no idea where to start with this one. We're using Better Exposed Filters module to allow checkboxes instead of dropdowns, etc. I already have a views-exposed-form template to handle the background color and font choices, etc. but aside from some kind of horrible hard-coding, I don't know how to get the icons from the taxonomy to display next to the checkboxes. I think I could probably move the css for this into the template file and generate a background property for each taxonomy term that would include the image, but I don't know how to get the image from the taxonomy term field in the context of the views-exposed-form template.

EDIT to add Views PHP code that worked

<?php
if(isset($data->field_field_hide_track[0]['raw']['value'])) {
    if($data->field_field_hide_track[0]['raw']['value'] == '0') {

    $image_vars = array(
        'path' => file_create_url($data->field_field_track_icon[0]["rendered"]["#item"]["uri"]),
        'alt' => $data->field_field_track_icon[0]["rendered"]["#item"]["alt"],
        'attributes' => array(
          'class' => array('session_list_track_logo')
        )
      );

    $track_logo = theme('image', $image_vars);
    print "
" . $track_logo . " " . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "
";
    }
    else {
      print "
" . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "
";
    }
}

?>

To show fields you have to use views_php where you can check

if ($row->field_hide_track) {
    print $row->field_track_icon;
}
For filters you are on the right track you are showing terms as checkboxes you just have to style labels of the field just like DrupalCon Denver's site something like this.

views-exposed-form-schedule-page .form-item-edit-track-1 label, #views-exposed-form-schedule-page-1 .form-item-edit-track-1 label, #views-exposed-form-schedule-page-2 .form-item-edit-track-1 label {

background: url(/sites/all/themes/denver2012/images/track-1.png) 0 0 no-repeat;
}


Set up varnish, but is the content really from cache? I set up varnish in my site and after the set up, checked the http header for an anonymous user. This was the response:

  Status: HTTP/1.1 200 OK
  Server: Apache/2.2.15 (CentOS)
  X-Powered-By:   PHP/5.3.3
  X-Drupal-Cache: MISS
  Cache-Control:  max-age=0, no-cache
  Content-Language:   en
  Link:   http://www.website.com/; rel="canonical",http://www.website.com/; rel="shortlink",https://plus.google.com/u/0/b/randomnumber/randomnumber/; rel="publisher"
  Vary:   Accept-Encoding
  X-Mod-Pagespeed:    1.6.29.7-3566
  Content-Encoding:   gzip
  Content-Type:   text/html; charset=utf-8
  Content-Length: 15365
  Date:   Sat, 08 Feb 2014 20:53:08 GMT
  X-Varnish:  658699528
  Age:    0
  Via:    1.1 varnish
  Connection: close

This is what isvarnishworking.com has got to say on this:

  Varnish appears to be responding at that url, but the Cache-Control header's "max-age" value is less than 1, which means that Varnish will never serve content from cache at this url.

This means that the purpose of me setting up varnish is not served. Is this correct? Varnishstat shows a hit to miss ratio of 50% which is good enough to start with:

83  Client connections accepted
     230  Client requests received
      21  Cache hits
      49  Cache misses
     210  Backend conn. success
     164  Fetch with Length
       1  Fetch wanted close
      39  N struct sess_mem
       1  N struct sess
      37  N struct object
      37  N struct objectcore
      26  N struct objecthead
      90  N struct smf
      16  N large free smf
       1  N struct vbe_conn
       2  N worker threads
      12  N worker threads created
  375315  N worker threads limited
     104  N overflowed work requests
       1  N backends
      12  N expired objects
       8  N LRU moved objects
     184  Objects sent with write
      82  Total Sessions
     230  Total Requests
     160  Total pass
     209  Total fetch
   84600  Total header bytes
 1377549  Total body bytes
       8  Session Closed
     223  Session Linger
     224  Session herd
   19641  SHM records
    1662  SHM writes
       1  SHM MTX contention
     213  allocator requests
      74  outstanding allocations
  409600  bytes allocated 10439155712  bytes free
     210  Backend requests made
       1  N vcl total
       1  N vcl available
       1  N total active purges
       1  N new purges added
      70  HCB Lookups without lock
      35  HCB Lookups with lock
      35  HCB Inserts
     752  Client uptime
      44  Fetch no body (304)

Here is a screeshot of the admin/configure/development/performance page:

http://awesomescreenshot.com/01e2bplzef

Your content is not from cache.

See the X-Varnish header;

X-Varnish: 658699528

If the content was served by Varnish, you'd have two numbers there. Not just one.

Have you looked at using the Varnish module? I'm not sure what version of Drupal you're using though.


Display Themed 'username' in Block I am trying to display the themed username in a custom block.

MyCustomBlock.php:

public function build() {

  $usersData = \Drupal::service('user.data')->get('my_module');

  $usersFromQuery = [];

  foreach ($usersData as $id => $value) {
    if (some logic) {
      $usersFromQuery[] = User::load($id);
    }
  }

  $userList = \Drupal::entityTypeManager()
    ->getViewBuilder('user')
    ->viewMultiple($usersFromQuery, 'compact');

  return $userList;

}

This gets me all the users I need, but not the altered/themed username I need.

In MYMODULE.module I am altering the username.

I've also tried:

$users = User::loadMultiple($userQuery);
User::load($uid)->getDisplayName()

but the username is rendered without hook_preprocess_username() alters.

I think the issue is similar to needing this: https://drupal.stackexchange.com/a/278717/79805

$variables['userName'] = [
  '#theme' => 'username',
  '#account' => $account,
];

but I am unsure how to get the themed username in my block.

How can I display the altered username in my block?

Update:

Using a helper function in MYMODULE.module that creates the markup for the altered username, and ->setUsername(), I am able to change the username in my custom block.

foreach ($usersData as $id => $value) {
  if (some logic) {
    $userItem = User::load($id);
    $userItem->setUsername(markup($id, $userItem->getUsername()));
    $usersFromQuery[] = $userItem;
  }
}

But is not really an answer to the question.

You invoke hook_preprocess_username() by rendering the template username. Since D8 has no longer a theme() function the only way to do this is by putting the template in #theme of a render array. In your case multiple times:

public function build() {
  $build = [];
  foreach ($usersFromQuery as $user) {
    $build[] = [
      '#theme' => 'username',
      '#account' => $user,
    ];
  }
  return $build;
}


How to implement StackMiddleware for a redirection correctly? I'm working on a redirection (for unauthenticated users) for my Drupal 8 site. Currently, the redirection works however, the redirection persists even after user is authenticated. I found this article piece helpful to point me in the right direction:

"Drupal 8 has two level cache, page cache and dynamic page cache. The issue you are having is more likely to intercept the page cache.
Add new class which implements 'HttpKernelInterface' and register 'http_middleware' with higher priority than 200 (280 will do)."

My problem is related to intercepting the page cache, so I am currently trying to implement the 'HttpKernelInterface' and register 'http_middleware' but unsuccessfully.
I created a custom module (example_module for example sake). My example_module.services.yml file:

services:
  example_module.event_subscriber:
    class: Drupal\example_module\EventSubscriber\RedirectAnonymousSubscriber
    tags:
      - { name: event_subscriber }
  example_module.stack_middleware:
    class: Drupal\example_module\EventSubscriber\StackMiddleware
    tags:
      - { name: http_middleware, priority: 210, responder: true }

Then in the same module I have a src/EventSubscriber/RedirectAnonymousSubscriber.php file like so:

<?php

namespace Drupal\example_module\EventSubscriber;
namespace Drupal\example_module\StackMiddleware;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface,HttpKernelInterface {
  private $redirectCode = 301;

    /**
  * The wrapped HTTP kernel.
  *
  * @var \Symfony\Component\HttpKernel\HttpKernelInterface
  */
  protected $httpKernel;

  /**
  * Creates a HTTP middleware handler.
  *
  * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
  *   The HTTP kernel.
  */
  public function __construct(HttpKernelInterface $kernel) {
    $this->httpKernel = $kernel;
  }

  /**
  * {@inheritdoc}
  */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    // Only allow page caching on master request.
    if ($type === static::MASTER_REQUEST && $this->requestPolicy
      ->check($request) === RequestPolicyInterface::ALLOW) {
      $response = $this
        ->lookup($request, $type, $catch);
    } else {
      $response = $this
        ->pass($request, $type, $catch);
    }

    return $response;
  }

  public function checkForRedirection(GetResponseEvent $event) {
    $is_authenticated = \Drupal::currentUser()->isAuthenticated();
    $route_name = \Drupal::routeMatch()->getRouteName();

    if (!$is_authenticated && $route_name !== 'user.login') {
      $response = new RedirectResponse('https://google.com', $this->redirectCode);
      $response->send();
      exit(0);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection',30);
    return $events;
  }
}

Do I need both an EventSubcriber and StackMiddleware to accomplish this redirection and intercepting of page caching?
Do I have to create a separate custom module to implement my StackMiddleware class? How do I use my redirection code (which I know works) with this StackMiddleware class so I can intercept the page cache and have it run on every page(so it always checks to see if user is authenticated)? Any help appreciated. Thanks!

I recently implemented this myself and had to do a fair bit of research and experimenting to get it to work. I too had many of the same questions you have so I've tried to answer them from what I've discovered.

Do I need both an EventSubcriber and StackMiddleware to accomplish this redirection and intercepting of page caching?

You will only need the "StackMiddleware" to intercept the page caching. It should replace "EventSubcriber" if that already exists.

Do I have to create a separate custom module to implement my StackMiddleware class?

This can be achieved in the same module.

How do I use my redirection code (which I know works) with this StackMiddleware class so I can intercept the page cache

The redirection function should be a called like so...

public function handle(...) {
  ...
  $this->checkForRedirection();
  ...
}

Have it run on every page(so it always checks to see if user is authenticated)?

In my case the user object wasn't available because the middleware runs prior to any user data being set. What I did have was the Drupal session cookie which I could check against. This cookie is set and unset depending if the user is authenticated or not. This may not be the most robust solution so others are welcome.

--
I found this article which was great for getting some of the foundations working:
https://chromatichq.com/blog/replacing-hookboot-and-hookinit-functionality-drupal-8


"COPY_ERROR: Unable to copy" while using drush make with download type "copy" Here is my module structure:

.
|-- mymodule.make
|-- mymodule.info
|-- mymodule.module
|-- mymodule.install
`-- sub1
    |-- sub1.make
    |-- sub1.info
    |-- sub1.module
    `-- sub1.install

I would like that when using drush make the sub-module sub1 is also made (so I would like that sub1.make is called too).

In mymodule.make I declare:

api = "2"
core = "7.x"

projects[drupal][version] = "7.39"

; Modules
projects[sub1][type] = module
projects[sub1][download][type] = copy
projects[sub1][download][url] = "./sub1"

And here is the error that I have:

Found makefile: mymodule.make                                [ok]
COPY_ERROR: Unable to copy sub1 from ./sub1. -- build forced [warning]

However, the documentation tells

  download[type] = copy Copies a project from a local folder.

so I think I'm using the correct [download][type]...

I've also tried with projects[sub1][download][url] = "file://./sub1" and have the same error.

As a workaround, I used the includes[] directive instead.

Here is my working mymodule.make:

api = "2"
core = "7.x"

projects[drupal][version] = "7.39"

; Modules
includes[] = ./sub1/sub1.make


Omega Theme, change content zone when sidebar had no content I'm using Omega as Base theme. In the content zone I have 2 regions:

'Content region' set as 9 columns
'Right column region' set as 3 columns

Is it possible to have a "flexible region"? I want to change the column count when the right column region is empty.

Yes, it is possible to change the column count for a region if another region is empty.

Go to the layout configuration of the Omega 3 Subtheme
Go to the zone that's the parent of the specific region
Set "Primary Region" to the region you want to give a flexible column count


Is it possible to do a drush sql-sync of only certain tables? I have 4 environments between my local, dev, staging, and production.

A large amount of content is published to the staging environment on a daily basis, so that is the center of my workflow. Once content is QA'ed in staging it is then sql-sync'ed to production. This works fine at the moment. However, we're now going to allow for user registration/user generated content. Is there a way to push these content updates with sql-sync and never overwrite certain tables? Even more specifically, is there something I can place in drushrc.php that will always skip a list of tables across all environments?

YES
If you know which tables you want to transfer

--tables-list
A comma-separated list of tables to transfer. Optional.

If you know which tables you want to skip

--skip-tables-list
A comma-separated list of tables to exclude completely. Optional.

And here is how I know this:

$ drush help sql-sync
Copy and import source database to target database. Transfers via rsync.

Examples:
 drush sql-sync @prod @dev                 Copy the DB defined in sites/prod to the DB in sites/dev.

Arguments:
 from                                      Name of subdirectory within /sites or a site-alias.
 to                                        Name of subdirectory within /sites or a site-alias.

Options:
 --cache                                   Skip dump if result file exists and is less than "cache" hours old. Optional; default is 24 hours.
 --create-db                               Create a new database before importing the database dump on the target machine.
 --db-su=                            Account to use when creating a new database. Optional.
 --db-su-pw=                         Password for the "db-su" account. Optional.
 --dump-dir                                Directory to store sql dump files in when --source-dump or --target-dump are not used.  Takes precedence over --temp.
 --no-cache                                Do not cache the sql-dump file.
 --no-dump                                 Do not dump the sql database; always use an existing dump file.
 --no-ordered-dump                         Do not pass --ordered-dump to sql-dump.  sql-sync orders the dumpfile by default in order to increase the efficiency of rsync.
 --sanitize                                Obscure email addresses and reset passwords in the user table post-sync. Optional.
   --sanitize-password                     The password to assign to all accounts in the sanitization operation, or "no" to keep passwords unchanged.  Default is "password".
   --sanitize-email                        The pattern for test email addresses in the sanitization operation, or "no" to keep email addresses unchanged.  May contain replacement patterns %uid,
                                           %mail or %name.  Default is "user+%uid@localhost".
   --confirm-sanitizations                 Prompt yes/no after importing the database, but before running the sanitizations
 --skip-tables-key                         A key in the $skip_tables array. @see example.drushrc.php. Optional.
 --skip-tables-list                        A comma-separated list of tables to exclude completely. Optional.
 --source-database                         A key in the $db_url (D6) or $databases (D7+) array which provides the data.
 --source-db-url                           Database specification for source system to dump from.
 --source-dump                             Path to dump file. Optional; default is to create a temporary file.
 --source-remote-host                      Remote machine to run sql-dump file on. Optional; default is local machine.
 --source-remote-port                      Override sql database port number in source-db-url. Optional.
 --structure-tables-key                    A key in the $structure_tables array. @see example.drushrc.php. Optional.
 --structure-tables-list                   A comma-separated list of tables to include for structure, but not data. Optional.
 --tables-key                              A key in the $tables array. Optional.
 --tables-list                             A comma-separated list of tables to transfer. Optional.
 --target-database                         A key in the $db_url (D6) or $databases (D7+) array which shall receive the data.
 --target-db-url
 --target-dump
 --target-remote-host
 --target-remote-port
 --temp                                    Use a temporary file to hold dump files.  Implies --no-cache.


Video Module Logo Question I have a question about configuring a player in the video module.

In the theme there's a video-play-html5.tpl template, which formats the JW Player.

The question is this--I've used the coding below, along with the pathauto module to change site logos based on content type:

    <?php
    // Return a file based on the URL alias, else return a default file
    function unique_section_header() {
      $path = drupal_get_path_alias($_GET['q']);
      list($sections, ) = explode('/', $path, 2);
      $section = safe_string($sections);
      $filepath = path_to_theme() . '/images/sections/header-' . $section .'.png';
      if (file_exists($filepath)) {
        $output = $filepath;
     }
      else {
        $output = path_to_theme() . '/images/sections/header-default.png';
     }
      return $output;
    }

    //Make a string safe
    function safe_string($string) {
      $string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
      return $string;
    }
    ?>

The question is, can something similar be done to change the watermark in the JW Player based on video content type in the html5 player template?  (This is assuming that the function even goes in the template;  I'm still learning my way around drupal.)

video-play-html5.tpl is primarily for the HTML5 player. Are you using JW Player with this template? I think you should use the JW Player module to use JW Player. Using preprocess functions you may be able to change the overlay path.


Phone international error in submit form I installed the module (international phone) on drupal 8.6 and I display it on my form.
when sending data it gives me an error message and blocks sending data.
The website encountered an unexpected error. Please try again later.
Error: Class 'libphonenumber\PhoneNumberUtil' not found in Drupal\phone_international\Helpers\ValidatingService->isValidNumber() (line 24 of modules/phone_international/src/Helpers/ValidatingService.php).
Drupal\phone_international\Helpers\ValidatingService->isValidNumber('+212670998765') (Line: 74)
Drupal\phone_international\Plugin\Field\FieldWidget\PhoneInternationalDefaultWidget->phoneValidate(Array, Object, Array)
call_user_func_array(Array, Array) (Line: 282)
Drupal\Core\Form\FormValidator->doValidateForm(Array, Object) (Line: 238)
Drupal\Core\Form\FormValidator->doValidateForm(Array, Object) (Line: 238)
Drupal\Core\Form\FormValidator->doValidateForm(Array, Object) (Line: 238)
Drupal\Core\Form\FormValidator->doValidateForm(Array, Object) (Line: 238)
Drupal\Core\Form\FormValidator->doValidateForm(Array, Object, 'node_candidat_edit_form') (Line: 118)
Drupal\Core\Form\FormValidator->validateForm('node_candidat_edit_form', Array, Object) (Line: 575)
Drupal\Core\Form\FormBuilder->processForm('node_candidat_edit_form', Array, Object) (Line: 318)
Drupal\Core\Form\FormBuilder->buildForm('node_candidat_edit_form', Object) (Line: 93)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

The error suggests that you haven't followed the installation instructions on the module page:

Since the module requires an external library, Composer must be used.
composer require "drupal/phone_international"


Unpublish node based on date field with Rules I'm trying to unpublish a node based on a date field with Rules.
I've followed this tutorial but somehow it doesn't seem to work.

Here's my Component:

{ "rules_unpublish_termin" : {
    "LABEL" : "Unpublish Termin",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "node", "type" : "node" } },
    "ACTION SET" : [ { "node_unpublish" : { "node" : [ "node" ] } } ]
  }
}

And here's the Rule:

{ "rules_unpublish_termin_rule" : {
    "LABEL" : "Unpublish Termin Rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert--termin" : { "bundle" : "termin" } },
    "IF" : [ { "node_is_published" : { "node" : [ "node" ] } } ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_unpublish_termin",
          "date" : [ "node:field-termin-datum:value" ],
          "identifier" : "Unpublish content ID [node:nid] ([node:title]).",
          "param_node" : [ "node" ]
        }
      }
    ]
  }
}

I'm fairly new to Drupal and I've never used the Rules module so I'm not sure if there's something else I'm missing here.

edit:
I've been looking into it a bit more.
Currently I have 3 nodes in this bundle with the following dates:
2018-01-09 (which should have been unpublished today)
2018-05-12
2018-07-14

In the Tab Schudule under admin/config/workflow/rules/schedule I can see that the component rules_unpublish_termin has a Schedule Date for 2018-07-14 00:00 which would correlate with the very last date, this seems a bit odd..

1. Timing of a scheduled Rules Component

After a rule is scheduled (using the Rules Scheduler, a submodule of Rules), it will only actually execute next time cron runs. Example:

schedule a rule to execute at timestamp X (which appears to be node:field-termin-datum:value in your case).
if the next time that cron runs is at Y mins after timestamp X, then the Rules execution will only happen then (= at Y mins after timestamp X).

BTW, as per the edit of your question, it seems that the Rules Component actually does get scheduled, and that your real issue is related to the execution of that scheduled component ... read on for more details about that.

2. Cron runs anonymous

Cron (always) runs with user anonymous, rest assured about that (in any Drupal 7 site). But here is an "educated" guess: your site is configured so that anonymous users are NOT allowed (= do not have the permission) to unpublish nodes.

Up to you to confirm if my guess is correct, but if it indeed applies, the answer to your question is that to get this to work you would need to grant anonymous users the permission to unpublish nodes. I bet it is not going to be what you want to do (I wouldn't ...), but trust me, that would be a prereq to make it all work in your site.

3. If everything else fails ...

If none of the above helps to find out what is causing your issue, then try either of these suggestions to get a better understanding of what is (not?) happening:

Try to execute your Rules Component "manually" (just to test), to unit-test if it works as desired, so without using the Rules Scheduler. To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).
Do some Rules debugging ... For way more details about that, refer to the answer to "How can I display the value of a variable inside a condition?".


Problem to display name from current logged I've created a custom block to display info from current user. When i'm logged with username "David", i see on my custom block the username from my last login with other user account.

I have to clear the cache to see the correct username from current user logged.

See here my code :

    class UserProfilBlock extends BlockBase {

  public function build() {

    $userinfo = [];

    $account = \Drupal::currentUser();
    $uid = \Drupal::currentUser()->id();

    $user = \Drupal\user\Entity\User::load($uid);

    $userinfo['name'] = $user->get('name')->value;

    return [
      '#username' => ucfirst($userinfo['name']),
      '#theme' => 'user_info_block',
    ];

  }

  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this->getConfiguration();

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['userprofilinfo_settings'] = $form_state->getValue('userprofilinfo_settings');
  }
}

Something is wrong on my custom module ?

I guess the problem is the block is cached for every user. You have to tell Drupal that it should be cached depending on the current logged in user. To do this you have to make use of Cache Tags.

In your case, you have to tell Drupal that the cache of that block should be invalidated when the current logged in user changes. That's because a Cache Context (the user) has changed.

How to do it? You are returning a Render Array, a structure that tells Drupal how to render certain data. In the render array you can set the cache contexts that affect this render array (if the context changes then the cached data changes). In the specific page that talks about the Cacheability of Render Arrays you can see an example of a render array that is cached for each user:

$build = [
  '#markup' => t('Hi, %name, welcome back to @site!', [
    '%name' => $current_user->getUsername(),
    '@site' => $config->get('name'),
  ]),
  '#cache' => [
    'contexts' => [
      // The "current user" is used above, which depends on the request,
      // so we tell Drupal to vary by the 'user' cache context.
      'user',
    ],
  ],
];

So, I guess that you should add the #cache key to your render array, probably in your theme function, but it may work in the build function (long time since I don't do theming, so I'm not sure).

The code to add is:

'#cache' => [
  'contexts' => ['user']
]


In drupal 7, for field widget type, what is "server side" used for? I created a new content type and added a text field.  While creating the text field I am given three options for the widget type: Server Side Only, Hidden Field, and Text Field.  The "Server Side Only" and "Hidden Field" come from the Hidden Field module.  Can someone explain when Server Side Only would be used?

I can't find any reference on Google to a widget that provides this type of functionality so I can only assume it's something custom, but I think the reasoning for it would be the same regardless:

When using the Drupal form API you can add an element of type value which keeps that element server-side only...i.e. the value is available to the form submission/validation functions but it not exposed to the user. A hidden field would still be exposed in the form's HTML so could theoretically be changed by the user before the form is submitted.

I would guess in this case it applies to the node edit form, each node would essentially have a non-editable field with a constant value. I'm not actually sure how useful this would be in normal life but I guess if every node had to have, for example, a geo-location map associated with it, and the value of that location field had to remain constant, this would do it. The same map would just be outputted on each node.

To be honest that could all be nonsense though, it's just an educated guess :)


How to add canonical links on ALL URL's? What is the best way to get canonical links on ALL URL's in D7?

I see nodes already have relative canonicals but I have a site with a lot of non node URL's that also need canonicals.

I added code to my html.tpl.php to add a canonical on any page but now I get double ups on node based pages.

Thanks for anyone taking a look at this.

UPDATE:
I used a theme_html_head_alter() hook to remove the node canonicals.
Then I added new canonicals into the html.tpl.php so every page has them and there is only one on the node pages.

As mentioned elsewhere, global redirect is a good option. But even Metatag is a good module. It not only handles the canonical urls but also meta keywords, description, Copyright data and many more important Meta data including OG. So, you can also have a check on this module. http://drupal.org/project/metatag and a tutorial on how to get the canonical url to work on this link: http://amitavroy.com/justread/content/articles/canonical-links-and-drupal-7

The one thing with meta tag module is that by default it will print relative canonical urls whereas I have seen major sites like smashingmagazine, engadget etc uses absolute. So, if you want that to happen then the second url is the key.


How can I redirect user/*/edit to another page based on user content? I have a site with the following relationship: for every user, there is one corresponding (node) profile. For the user/*/edit, I would like the user to actually edit their profile node, not the user account. I've thought about preprocessing the page template to make something available in order to then re-write the secondary menu in the template - but which variable can I use? It's not available in the $user array.

So in broad strokes, basically what you want to do is grab the user's uid and then open for editing the corresponding profile type node owned by that user.

So, if you have that user's uid in $uid, it would be something along these lines:

$nid = db_select('node', 'n')
        ->condition('n.type', 'YOUR_PROFILE_NODE_TYPE')
        ->condition('n.uid', $uid)
        ->fields('n', array('nid'))
        ->execute()->fetchField();

which, if I've not typo'ed anything will set $nid to the node id of the node of type YOUR_PROFILE_NODE_TYPE that is owned by $uid.

If there is only one, that's the node we are looking for.

So, now you just need to create a link to node/$nid/edit and you're all set.  (Somewhat obviously, you want to present this link only to admins and the user who owns the profile.)

So, where do you put all of this?

Of course, you could preprocess this into a variable that's used in a page template, but you could also create a new menu item as well, eg user/#/edit-profile that grabs the user id out of the second argument and then does all of the above to grab the actual nid and then presents the node edit form, but now we are getting past the broad strokes :)  (But hook_menu() is the place to look, with user.module a great starting point for example code for user/#/edit to modify)


How to get programatically 'display_options' for a specific page in Views I am a bit confused on how I should code this...
I have a view based on a custom content entity with 4 displays: default (hidden), Page (page_1), Export Entité (rest_export_1) and Export pour Maps (rest_export_2).

Devel shows this for this view:

I'd like to get the value of the path for 'rest_export_1' to use it in $name.
My code:

function association_exportCSV($view, $page)
{
  $view = \Drupal\views\Views::getView($view);
  $name = ???
  $page = $view->preview($page);
  file_unmanaged_save_data($page , 'private://' . $name . '.csv', FILE_EXISTS_REPLACE);

}

What should I do next? How to get $name from 'path'?

Try with:

function association_exportCSV($view, $page) {
  $view = \Drupal\views\Views::getView($view);
  // $display_id in this case is  'rest_export_1
  $view->setDisplay($page);
  $path = $view->getPath();
  file_unmanaged_save_data($page, 'private://' . $path . '.csv', FILE_EXISTS_REPLACE);
}


How to use long file description? Is there any easy way to store a long text description of an uploaded file?

I want to provide a long description field (textarea) when users upload files, so they can write as much as they need. Current title field is limited to 255 chars.

Any ideas on how to do this?

Thanks!

Edit 1

The file_entity module does not support Inline Entity Form unfortunately, so this solution won't work.

Here are the related issues on Drupal.org:
https://www.drupal.org/node/2038053
https://www.drupal.org/node/2327369

The Inline Entity Form pushed me in the right direction.

Here's what worked for me:

Install File Entity module. It will allow you to add fields to files, in my case a "Description" textarea field.
Install File Entity Inline module. It will allow you to optionally include some of the fields directly in the file upload widget.
Add a file field and on configuration page under "Inline fields" choose either "All available fields" or "Only selected fields".

That's it - hope this helps someone!


How do I receive security updates? On my client(s) website,  I turned the update module on.  From time to time, they receive an error message on every page about a security update.  They complain about this message, and they don't want to see it, so I turn the module off.  I still want to keep up-to-date with all the security upgrades.  How do I make sure I receive security updates?  Is there a feed,  an email list?

All security announcements are posted to an email list as well. Once logged in, go to your user profile page and subscribe to the security newsletter on the Edit » My newsletters tab.

You can also get rss feeds for core, contrib, or public service announcements.


Insert code in to field or center of content type that already has 1000's of nodes So i'm trying to put Google Adsense in to the middle of a node of a few different content types and have tried does this in various ways but to no avail.

The latest method was to put the google adsense in to a block, which works and then use block reference module as a field, this bit works too which in turn shows the google adsense in the exact place I want it, above certain fields and next to the main body field. The problem with this method is that I want it to show on every node already created, which there are thousands of. I have used https://www.drupal.org/project/field_defaults to select the block on that field and to force it to show on all already created nodes, but this last bit doesn't work. I still have to go through the nodes individually and add the block reference.

Another method I tried was to create a field called Google Ad Content and then add the default google adsense code, as above, this doesn't work because I have to preselect the text format to work with the google adsense code and also update all of the nodes and I end up with the same problem as above.

How else can I go about this?

https://www.drupal.org/project/eba inserts a block in to the manage display area of each node or entity, this has allowed me to add a google ad in the middle of the content between any fields I want on any entity I want and to 1000s of already published nodes.


Conditional form states in hook_form_alter() I have a node with a field, whose widget uses select boxes and multiple choices are possible. The values are coming from a taxonomy entity reference field. There is another field, a text field, which needs to be hidden.
/**
 * Implements hook_form_alter().
 */
function mijn_condities_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if($form_id == 'node_bedrijf_form' || $form_id == 'node_bedrijf_edit_form'){
    $form['field_afstand']['#states'] = array(
      'visible' => array(
        ':input[name="field_openbaar_vervoer"]' => array('value' => '236'),
      )
      );

  }
}

A select box should be added according their choice. For example, when they choose bus or tram, there should be a field to enter the distance in meters. When they choose airport, the range must be in kilometers.
The field isn't hiding.
I already tried to make the field invisible, but this doesn't work.
Does anyone know what is wrong?

This is a little bit tricky the Form API #states works with jQuery selectors if your filed field_openbaar_vervoer coming from a taxonomy entity reference.
So the input generated HTML will be something like (example from tags fields)
<input data-drupal-selector="edit-field-tags-3" aria-describedby="edit-field-tags--description" type="checkbox" id="edit-field-tags-3" name="field_tags[3]" value="3" class="form-checkbox">

So to target all those inputs you should use Starts With Selector in your code and it will work:
$form['field_afstand']['#states'] = [
  'visible' => [
    ':input[name^="field_openbaar_vervoer"]' => ['value' => '236'],
  ],
];


Display nodes under Parent Taxonomy in Views I am using Drupal 7, and I created a two-level vocabulary used it as a field for term reference. I created it using
Simple hierarchical select module.

edit : I have my node tagged with both the parent(State field), and child (City field) term.

Location

 - State1
   - City A
   - City B
 - State2
   - City C
   - City D

Then I have a page View, where I use the Location field as an exposed filter, so that visitors can sort the content.

I have no problem in getting the results when the user selects for example:

  Illinois

  Chicago

Then all content that has the term Illinois and Chicago will be displayed.

The problem comes when I only want to sort using the parent term, so if you sort for example using only

  Illinois

It should display every node that has the term Illinois.  But my Views returned nothing, when selecting only the parent term and applying that exposed filter.

I have checked that when you look view the taxonomy of Illinois everything displays properly, but not on the exposed filter in Views.

How will I proceed on displaying the nodes in my Views using exposed filters?

I have managed to work this one out.

Apparently you can add a filter using two methods:

"Simple hierarchical select"
"Content: Has taxonomy terms (with depth; Simple hierarchical select)"

Select the second method Content: Has taxonomy terms (with depth; Simple hierarchical select) as the filter.

Then after selecting the filter, you then have the option to select which taxonomy term to use. After that just select Simple hierarchical select.

Next step was to just simply expose the filter to users, so they can manipulate it.


Rules Link - Insert into System Node Content Template Variant I'm trying to incorporate a Rules Link into an edited Panels Node Template Variant (Structure -> Pages -> Variant). The Rules Link is a simple "Apply Now" but I'm a little confused as to what I should be inserting as a Content. Previously it was working fine (the Rules Link added to the Content Node Field set and when any said content type was viewed it was there).

This item when I look at the content types available (Activity through to Widgets), I select Form (and available content) or Node or Node Token Type), all I get on the saved Node Template when viewing is basic text 'Entity info.' in the said Block and no actual Rules Link (ie general 'blue' URL link).
My efforts to get it to show in the Node Variant is not a success and I've tried the Content types available for insert. I roughly understand what is happening and how things 'should' work and presumed what I did before would merely work in the edited Node, it seems quite self explanitory but not having much joy at this stage or maybe I'm merely missing a small point.

Could someone share with us the general process of getting a Rules Link to show in a Node Content Template Variant in order for the Rules Link to process to the next stage. Thanks.

I appear to have found the answer to my original question above and solved it, though I'm not too sure if it would be the ideal (correct) approach, but it's ideal for now.
After reading this post Use content panes as blocks I approached my issue by using a Mini Panel to include the said Rules Link, it worked fine.
Put simply, I just created a Mini Panel, included the Rules Link as Content (see how in the above post), saved, then went back to my original Node Template Panel Variant, edited and included as a new Content in the Panel Editor, then saved that Panel. Voila!

You may have to fiddle with the Override Panel headings etc to get rid of any unwanted shown text: i.e Panel Name (I justed wanted the Link URL to trigger workflow and not the actual Mini Panel Title, so use the 'Override' Title option). It couldn't be that easy? well it is.

Sometimes I think we may over complicate Drupal, now in my opinon we shouldn't, we just need to see the wood from the trees. Clearly I'm learning Drupal, so will you.


entity_get_form_display setComponent throws "plugin does not exist" regardless of type I'm trying to programmatically add a field to a custom bundle, and have it appear on the custom entity type. I'm using a BaseForm extended class, and have acquired an entityManager elsewhere using dependency injection.

Below is the submitForm() code I modelled, on how FieldStorageAddForm::configureEntityFormDisplay() etc. works:

$field_storage_values = [
  'field_name' => 'field_phone',
  'entity_type' => 'contact',
  'type' => 'string',
  'translatable' => false,
];
$field_values = [
  'field_name' => 'field_phone',
  'entity_type' => 'contact',
  'bundle' => 'organization',
  'label' => 'Phone',
  'translatable' => false,
];
$this->entityManager->getStorage('field_storage_config')
    ->create($field_storage_values)->save();
$this->entityManager->getStorage('field_config')
    ->create($field_values)->save();

entity_get_form_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'string_textfield'])
  ->save();
entity_get_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'string_textfield'])
  ->save();

This works fine for adding the field storage, and for associating the field instance with the bundle.

However, when it gets to the entity_get_form_display()->setComponent()->save(), the following exception is thrown:

Uncaught PHP Exception Drupal\\Component\\Plugin\\Exception\\PluginNotFoundException: "The "string_string_textfield" plugin does not exist."
at /var/www/web/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 60

What's strange is that the same exception, quoting 'string', is seen for both 'type' => 'string_textfield' and 'type' => 'text_text_with_summary' (which doesn't even contain the word 'string'!) On the other hand, a nonsense value (e.g. 'string_string_textfield' or 'stringz_textfield') yields the exception with the nonsense value in full, no parsing. So there's some kind of detection/lookup going on, but it still can't find the relevant plugin.

What am I missing? What should the value of 'type' be? I'm aware of e.g. https://drupal.stackexchange.com/questions/177913/the-string-plugin-does-not-exist but as you can see the value suggested there doesn't seem to work in this situation.

OK, I've dug around and I think I've got a fix for this myself.

The first thing is to fix the code above; the two 'type' entries SHOULD be different, and should match values available in the dropdowns in the admin UI:

entity_get_form_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'text_textfield'])
  ->save();
entity_get_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'string'])
  ->save();

The second thing is that the entity's baseFieldDefinitions() were also defining a 'view' formatter type and a 'form' formatter type, but for an undeletable base field:

$fields['name']->setSettings([
    'default_value' => '',
    'max_length' => 255,
    'text_processing' => 0,
  ])
  ->setDisplayOptions('view', ['label' => 'above', 'type' => 'string'])
  ->setDisplayOptions('form', ['type' => 'text_textfield'])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Originally, the form display here was also 'string'. This is obviously nothing to do with the programmatic field adding itself, but when you run:

entity_get_*display(...)->setComponent(...)

the return value is $this i.e. the display object. So chaining ->save() causes the ENTIRE display to be saved: including base fields. Only at this point did the broken configuration in the base fields suddenly cause a problem.

But, ensuring that:

the 'type' for form display ALWAYS matched a value available in the admin UI for content types
and similar for view display
and ensuring this across both the new field AND base fields

fixed the original problem. Phew.


How to make a carousel with 1 highlighted node and thumbnails left and right? I'd like to make a carousel exactly like the picture below, 6 thumbnail node on the left side, 1 highlighted node in the middle and again 6 thumbnail node on the right side, and when the user clicks on the controls, the next set of nodes shows up.

I guess it must be possible to achieve this with the output of the views and using a module like OwlCarousel to achieve this, but so far I couldn't make it work! I'd really appreciate a full detailed answer.

You could do this with the jCarousel module:

Build your view to show the required nodes in the order you wish them to show.
Enable jCarousel view format
Create a style output template using a file name from OTHER -> Theme: Information -> Style output
Copy the code from the style template offered by the jCarousel module
Change the template code to output 7 rows at a time with the necessary wrappers and classes to make it look like your design
Make sure the .jcarousel and .jcarousel-clip divs are outside each group of 7 rows. [edit: it appears this happens outside of the template file, so not usually something you'll need to worry about]

Here's something to get you started with the style template file:

<?php

/**
 * @file jcarousel-view.tpl.php
 * View template to display a list as a carousel.
 */
$count = 0;
$rowcount = count($rows);
?>
<ul class="<?php print $jcarousel_classes; ?>">
  <?php while ($count < $rowcount): ?>
    <li class="<?php print $row_classes[$id]; ?>" style="display: none;">
      <?php // Print your seven rows here ?>

      ...

    <?php // Advance the counter ?>
    <?php $count += 7; ?>
    <?php // Depending on how you print your rows you may wish to slice 7 items off the $rows array ?>
    <?php $rows = arracy_slice($rows, 7); ?>
  <?php endwhile; ?>

Note that if you're referencing each row like $row[id] you may need to do a check before printing each one unless you're certain there will be a multiple of 7 rows in your view.


Are there Get/Set methods for addressing commerce line_items and order object properties? Are there get/set functions/methods for all line item and order properties?

I find myself manipulating line items thus:

$line_item->commerce_unit_price['und'][0]['currency_code'] = $whatever;

I was thinking there must be a better way to (ie. without addressing array members?) My concern is that the structure may change as Commerce develops.

What you're doing is correct for Commerce 1.x.  Drupal 7 just uses stdClass objects for entities, no methods. Fortunately Commerce 1.x isn't seeing any significant changes - any time we make an API change it will be heavily noted in the change log of a new release. Additionally, Commerce 2.x on Drupal 8 is actually able to use robust classes for entities, so the future is brighter.


Is it possible customize user login page on Adaptive Theme? I tried many solutions for change my mysite.com/user page. I want, only login-register-forgotten form is visible, other block hidden. But what i try a solution, don't working.

Is it possible? How can i do this?

This is my past question: https://drupal.stackexchange.com/questions/65475/error-when-creating-a-custom-page-in-d7

If you wish to hide blocks, go to the block configuration page (/admin/structure/block), celect 'configure' for the blocks you wish to hide, and under 'Block Visibility Settings' on the 'Page' tab select 'All pages except those listed '. Then if your login url is '/user/login', enter 'user/login' in the box. If you enter 'user/*' it will exclude the block from all pages matching the pattern.


Lazy Load inline images in Drupal 8 We have nodes with a lot of inline images in them. And we are looking for a solution on how to lazyload inline images in Drupal 8.

We are trying to get the Blazy module to lazyload them but it is not working that smoothly since we have a ton of posts already and can't manually apply the src-data attribute and class to all existing images.

This is how I am trying to get blazy to lazyload all images, but it is not working. Any ideas on what we are doing wrong? We are open to all recommendations.

Apply lazyload / blazy to all images.

1) In mytheme.libraries.yml I added the following:

dependencies:
- blazy/load

2) In MYTHEME.info.yml I added the following

libraries:
- 'mytheme/global-styling'
- 'mytheme/local'

3) In MYTHEME.theme I added the following:

/**
* Implements hook_page_attachments_alter()
*/
function MYTHEME_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'blazy/load';
}

What is wrong?

Currently getting this error:

  Fatal error: Cannot use assign-op operators with overloaded objects
  nor string offsets in
  /core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php on line 138

When you need to lazy-load inline-images, I'd recommend doing that so via Filter plugin system.

That way you wouldn't need to alter any of the HTML in the node body/content.

The filter would be responsible of making the necessary markup changes to support lazy loading images.

The filter plugin should be FilterInterface::TYPE_TRANSFORM_REVERSIBLE type to avoid making changes to node content. That way in CKEditor the images could be maintained same as before. But when they are viewed in the page they would be lazy-loaded.

Here's the plugin I created for my projects:

<?php
// This plug needs to be placed in a custom module:
// `modules/custom/YOURMODULE/src/Plugin/Filter/FilterLazyload.php`

namespace Drupal\YOURMODULE\Plugin\Filter;

use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Provides a filter to lazy-load images.
 *
 * @Filter(
 *   id = "filter_lazyload",
 *   title = @Translation("Lazyload images"),
 *   description = @Translation("Lazy load images via bLazy"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE,
 *   weight = 20
 * )
 */
class FilterLazyload extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    $placeholder_src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';

    $result = new FilterProcessResult($text);
    $html_dom = Html::load($text);
    $images = $html_dom->getElementsByTagName('img');

    foreach ($images as $image) {
      $src = $image->getAttribute('src');
      $image->removeAttribute('src');
      $image->setAttribute('data-src', $src);
      $image->setAttribute('src', $placeholder_src);
      $classes = $image->getAttribute('class');
      $classes = (strlen($classes) > 0) ? explode(' ', $classes) : [];
      $classes[] = 'b-lazy';
      $image->setAttribute('class', implode(' ', $classes));
    }

    $result->setProcessedText(Html::serialize($html_dom));

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function tips($long = FALSE) {
    return $this->t('All inline-images will be lazy-loaded.');
  }

}

You still need to attach bLazy library and the initiator js to all pages. But you don't necessarily need the Blazy module to make this plugin work.


Content Access module hiding menu links I am using Content Access module with Drupal 7. when i restrict node access from a specific role, it also hide link in menu.

is there any way to show restricted links in main menu?

The main purpose of the access content system is to have control of what every user can see and avoid every possible security issue. This is the desired behavior and almost every module or general ApI uses it, so you won't find default solutions for this.

I've been in the same situation and the only solution I found was to create a custom modules and, in my case, query directly to the menu table to get all the elements I want, and check the permissions myself to either display a link, or simply a title of the content when the user don't have permissions to see it.


How do I exclude a bunch of nodes from being indexed by Solr? I want to remove unused nodes from indexing in solr and also I need to make sure that they are not indexed again. I will fetch the list of the unused node IDs using a query.

If any of the nodes is getting updated, then I need to index that node again.

How can I achieve this?

For d7 you are looking for the hook: hook_apachesolr_exclude

Example from the apachesolr.api.php

/**
 * This is the place to look for the replacement to hook_apachesolr_node_exclude
 * You should define a replacement for the status callback and return
 * FALSE for entities which you do not want to appear in the index and TRUE for
 * those that you want to include
 */

/**
 * This is invoked for each entity that is being inspected to be added to the
 * index. if any module returns TRUE, the entity is skipped for indexing.
 *
 * @param integer $entity_id
 * @param string $entity_type
 * @param integer $row
 *   A complete set of data from the indexing table.
 * @param string $env_id
 * @return boolean
 */
function hook_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
  // Never index media entities to core_1
  if ($entity_type == 'media' && $env_id == 'core_1') {
    return TRUE;
  }
  return FALSE;
}

See here: http://drupalcontrib.org/api/drupal/contributions%21apachesolr%21apachesolr.api.php/7

UPDATE

For deleting certain nodes (entities) you can use apachesolr_remove_entity.


theme ALL form elements in a tpl through hook_preprocess_HOOK Trying to theme a form into all the pieces available, passed my $form and $vars through hook_preprocess_HOOK but in my tpl i would like the exact render() representation of the fields and variables and the form itself like:

print $form_tag.
      $form_input1.
      $form_input2.
      $theme_var1.
      $form_closure; <!-- build_id,token_id -->
 ?>

Where there are declared in the preprosess_HOOK as

$form = $variables['form'];
$variables['form_tag'] = render($form);
$variables['form_input1'] = render($form['input1']);
$variables['closure'] = drupal_render_children($form);
...

Is it possible to have all this variables of produced HTML in my tpl?
 like form start tag and closure and render correctly all the inner fields?
Thank you

I am not sure if this is what you are trying to do. But from the question I feel that you just want to re arrange the form in an order of your choice.

The best place to do that is with in a hook_form_alter function. Rather than the preprocess_HOOK.

Every form element has a property called #weight This could be used to arrange the forms in order the one with higher weight would go down.


Is it possible to style a Views 'group by' field that's excluded from display? I'm working on a glossary view. I have created letter headers by rewriting a copy of the term title, limiting it to 1 character, excluding it from display, and using that as the "Group By" field. The field is then shown by Views, but it doesn't contain the <h2> tag that I wrapped around the field in the rewrite rules. The normal term titles are output (by default) with <h3> tags. I would like the letter headers to be larger, but since Views seems to be overriding everything, I can't see how to do accomplish this.  It doesn't even output the class name I attached to the field.

Any ideas?  Your help is appreciated!

Under the advanced tab you can see what templates you need to override the views template. Copy the templates mentioned from the modules/views/themes folder to you own theme/templates folder, rename them as the view suggests under advanced and style your output.

note: if you display a teaser or full node, but forced it to use fields, the styling (making it h3) won't work.

The h3 is coded in views-view-unformatted-list.tpl.php. The $title there is output of the field you grouped by. There you can set it to h2.

UPDATE:
This is the default views template for outputting lists (the container which contains all rows as a group). This one is named views-view-unformatted.tpl.php, you need to rename it to match with your view.

 <?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>
 // THIS IS THE GROUPNAME
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?> // THESE ARE THE ROWS INSIDE THE GROUP
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

If you want to put style on ALL the rows inside the group then you can use the view-ui itself, or use the template called views-view-fields.tpl.php to override all rows.

If you want to style ONE specific row use views-view-field.tpl.php (note there is no 's' behind field).


Can I organize my custom module's twig templates into subfolders? My module now has a lot of TWIG template files in the /custom/MYMODULE/template folder. I tried creating some sub-folders because I thought Drupal 8was supposed to search all sub-folders automatically but I got an error about a missing template file. Should it work?

I've tried setting the subfolder name in '#theme' => 'SUBFOLDER/mytemplate' and I don't get an error, but the block contents are just blank (although the title displays).

I have my template defined in MYMODULE_theme(), but it feels wrong to specify a sub-folder in there.

This is what the docs for hook_theme say about the template property:

  If specified, the theme implementation is a template file, and this is the template name. Do not add 'html.twig' on the end of the template name. The extension will be added automatically by the default rendering engine (which is Twig.) If 'path' is specified, 'template' should also be specified. If neither 'template' nor 'function' are specified, a default template name will be assumed. For example, if a module registers the 'search_result' theme hook, 'search-result' will be assigned as its template name.

Unless you've found a bug of omission, I would expect these docs to tell you if there was any auto-scanning of sub-folders going on. The fact that you've tried it and it doesn't work might be seen to back that up.

If you've seen other official docs that reference an auto-scanning feature, you may have hit a bug.

As an aside, I'm not sure what the intent of this code is:

'#theme' => 'SUBFOLDER/mytemplate'

You would never write that; you would instead use hook_theme to register your template with the system, and put the path to the file itself in the template property. Then you'd use:

'#theme' => 'theme_key'

in the render array


How do I integrate media (e.g. attaching audio) to nodes? I installed the Media Entity module for Drupal 8. I thought it would somehow facilitate adding Mp3, etc, as Media does in Drupal 7, where I could specify a media player type for an audio file. (And things work fairly well.) I am updating my site to Drupal 8 and it seems the Media Entity module only acts as an API. Maybe I just need to wait for an official Drupal 8 release before I get too far in the weeds with media?

Since I am grabbing Mp3 files from my previous site, ideally there would be a media field to which I can, in code, just add the field info, with the rendering of the field being determined by the form display settings.

Anyway, I am sure a lot of people are trying to figure this out in Drupal 8, so if anyone has a good approach, I am all ears!

To use mp3 files with Media entity you need the additional module "Media entity audio".

Alternatively, you can attach audio straight to nodes with the "Audiofield" module.


How to use contact module of Drupal 7? I want to use drupal 7 core module for contact.
I want to use it as block so that I can add a contact form to the right sidebar of your website which should be shown at every page. or render it anywhere in the page
I saw this on drupal site and tried to use it.

<?php
print drupal_get_form('contact_mail_page');
?>

It is showing me this

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'contact_mail_page' not found or invalid function name in drupal_retrieve_form() (line 841

So any suggestion how I can use this.

use this code

<?php
if(!function_exists('contact_site_page')) {
  require_once drupal_get_path('module', 'contact').'/contact.pages.inc';
  $output = drupal_get_form('contact_site_form');
  print drupal_render($output);
}
?>

and put print drupal_render($output); where ever you want to put the contact form.

as another solution you can also assign a region for where you want the contact form to be then place the form in there.


Drush makefile downloading 7.x Dev instead of stable I have drush makefile that I use to kick off new Drupal installs:

my_profile.build

core = "7.x"
api = "2"

projects[drupal][version] = "7.x"
; ... grab install profile

When I run drush make my_profile.build it downloads the 7.x-dev version of core instead of stable. I knew that I code force the download of dev versions with projects[drupal][version] = "7.x-dev" but how do I make sure that it only downloads the stable version of a project? My drush version is 5.7.

To always specify the latest major version of Drupal, just use

projects[drupal][version] = 7

For modules and themes, just omit the version. For example:

projects[views][type] = module


How to Add "Add to cart" Button in product categories display I display my products through the category menu, so that when you click it, it shows the list of all the items in that category, ie:
http://website/product-category/pasta

I want to have an "add to cart" button below the image and descriptions of every single items.

How can i do that?

thank you.

Here's the code I that built the add to cart button using a specific product_id:

<?php

$form_id = commerce_cart_add_to_cart_form_id(array($product->product_id));
$line_item = commerce_product_line_item_new($product);
$line_item->data['context']['product_ids'] = array($product->product_id);

$form = drupal_get_form($form_id, $line_item);
// render your $form somewhere

?>


Checkout page not found when order created through Drupal Commerce API for not authenticated (anonymous) user I have the following code inside rules - action (being triggered by webform submission)

<?php
global $user;
$product_id = 1;

// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
$order = commerce_order_new($user->uid , 'checkout_checkout');

// Save the order to get its ID.
commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

// Redirect to the order's checkout form. Obviously, if this were a
// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);
?>

the code works perfectly when i am logedin, however when i submit the webform as not authenticated user, i get sent to checkout/12, I get page not found.

there is no errors in the log, and i see in the backend that the order was created... please help...

You need to add the order to the session, see commerce_checkout_access().

Something like this should work:

$_SESSION['commerce_cart_orders'][] = $order->order_id;

between saving the order and redirecting.


How can I send html email notifications with entityforms? There must be a way to do this, but I'm having trouble turning it up.  Has anyone successfully sent HTML email notifications following an entityform submission?

Here some more detailed guidance on how to solve this:

HTML EMAILS

You will need to download and set up Mime Mail.

The latest version of Entity Form (currently 7.x-2.0-rc1) comes with it's own preconfigured rules. You'll need the Entity Rules module for these. You can clone or edit these.

Alternatively you can set up your own fresh rules in the 'normal' way by using the 'After saving a new entityform submission' event.

Whichever method you go for you will need to add the 'Send HTML e-mail' element to the Actions stage of the rule (you can remove the existing actions if you cloned the packaged entity rules).

You can configure KEY, TO, CC, BCC, SENDER NAME, SENDER E-MAIL ADDRESS, REPLY E-MAIL ADDRESS, SUBJECT, BODY, PLAIN TEXT BODY, ATTACHMENTS, LANGUAGE.

EMAIL FILE ATTACHMENTS:

A lot of people have trouble getting file attachments to work with Entity Forms.

To do this:

Edit the action and within the attachments section you can add a file path token, e.g.

[entity:THE_FILE_FIELD_NAME:file:path]

Check the Replacement Patterns for the field name and make sure you use 'file:path' as above and you will get an attachment on the HTML email.

Other file tokens include:

[entity:THE_FILE_FIELD_NAME:file]

[entity:THE_FILE_FIELD_NAME:file:url]

[entity:THE_FILE_FIELD_NAME:file:size]

You may wish to use these in the email body for example.

Here is a list of file tokens. There are other useful tokens listed on there too.


Webform can't display the form Webform can't show the form.

The form is showing correctly until today I just found out the form can't display.

It shows me the message "You may not submit another entry at this time."

How do I solve it?

Drupal 6

I made the changes for Total submissions limit: Unlimited, but still same problem.

After made the changes, error message below shown:

  user warning: Unknown column 'total_submit_limit' in 'field list'
  query: UPDATE webform SET nid = 110, confirmation = '',
  confirmation_format = 3, redirect_url = '', status = 1,
  block = 0, teaser = 0, allow_draft = 0, auto_save = 0, submit_notice =
  1, submit_text = '', submit_limit = -1, submit_interval = -1,
  total_submit_limit = 10, total_submit_interval = 3600 WHERE nid = 110
  in /home/domains/site.com/public_html/includes/common.inc on line
  3538.

Try to update your database with update.php (http://www.YOUR-DOMAIN.com/update.php) or with drush : drush updb
The error says that your are missing one column in DB...


How can change RealName / User account link destination in D7 I'm using RealName module in D7 to show real names on nodes and in comments and would like to link the real name [user:first-name] [user:last-name] to a custom content type (a 'profile' page), instead of the standard 'user account'.

It is easy to use RealName in D6, but I've been searching for ages for a solution in D7.

I have read "Have username link to profile rather than regular userpage by default", but I am not using Content Profile.

I wondered if I need to 'preprocess' the user name, but can only read php and have no idea what to change there.

I have set the URLs for account pages to be [user:first-name]-[user:last-name]-account using URL alias patterns and the URLs of the custom content type I am trying to link to look like [user:first-name]-[user:last-name].

What is the simplest way to change the 'View user profile' link, which appears in comments and in node 'Authored by' to point at my custom user profiles instead of the standard 'user account's pages?

Did you try hook_username_alter in Drupal 7.

  Alter the username that is displayed for a user.

  Called by format_username() to allow modules to alter the username
  that's displayed. Can be used to ensure user privacy in situations
  where $account->name is too revealing.

I've used this occassionally, but I find sometimes there are instances where I felt it should have been called/used already and then wasn't (the Webform module submission report tables come to mind ...)


How to solve Mysql PDOException: SQLSTATE[42S02]: Base table or view not found: I have created form to add general information about daily work. When I submit this form it will give me following error. Please help me. I have checked my setting.php. There prefix is drup_

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'i1164525_drup1.drup_drup_Detailstable' doesn't exist: INSERT
  INTO {drup_Detailstable} (Username, Email_Id,
  Work_Location,Team_size,Total_hours,Date,Description,Verified) VALUES
  ('admin','swap@mm.com','abc','1','20','12/12/2014','Test','Not
  Verified'); Array ( ) in eval() (line 43 of
  /home/csrdiarycom/public_html/modules/php/php.module(80) : eval()'d
  code).

 <form name="form" method="post" action=''<?php echo $_SERVER['PHP_SELF']; ?>">
 Work Location
 <input type="Text" name="location" value=""/>
 Individual/ Number of people
 <input type="Text" name="numberofpeople" value=""/>
 Date
 <input type="Text" name="date" value=""/>
 Total Time spend by You/Team(In Hours)
 <input type="Text" name="Totalhours" value=""/>
 Your Experience
 <textarea row="5" maxlength="200" cols="30%" name="comment">Type here</textarea>
 <input type="Submit" name='Submit'/></form>
 <?php
 if(isset($_POST['Submit']))
 {
   $location=$_POST['location'];
   $numberofpeople=$_POST['numberofpeople'];
   $Totalhours=$_POST['Totalhours'];
   $date=$_POST['date'];
   $comment=$_POST['comment'];
   db_query("INSERT INTO {drup_Detailstable} (Username, Email_Id, Work_Location,Team_size,Total_hours,Date,Description,Verified) VALUES ('$e','$e','$location','$numberofpeople','$Totalhours','$date','$comment','Not Verified')")->execute();
  echo "
Thank you for your Comment!
";
  }}
  ?>

Remove the 'drup_' prefix from your db_query call. Since you define a prefix in settings.php, using {Detailstable} will automatically add the prefix on lookup.


Display another field as 'Node author' if node posted anonymously Currently on my D6 site registered as well as anonymous users can post articles. A custom text field has to be filled by unregistered users while creating an article. This text field's value is shown as Node author for anonymous posters.

Now I am all set to upgrade this site to D7. I tried using the following snippet to display custom text field value as the 'node author' if posted by Anonymous user, But it has some issues...

menu_get_object() works only for full node view and not for teasers etc.
It also changes $name every where on the page eg: for unregistered comments too.

function mytheme_username_alter(&$name, $account) {
  $node = menu_get_object();
    if($account->uid == "0") {
      $name = $node->field_custom_author['und'][0]['value'];
     }
}

Question: How can I tweak this function to display custom text field's value as 'Node Author' if the node is created by an anonymous user, without changing $name elsewhere on the page?

If there's a better function/solution than this, i am all open to try that too.

You have two viable options:

In theme system, use either node.tpl.php file to do it, or probably better template_preprocess_node(&$variables). I'll discuss function as that's what I prefer. When using function, copy it to your own template.php, renaming to mytheme_preprocess_node(&$variables). As a source, use parent theme if it implements it. If not, or if there is no parent theme, use link I provided above.

Then find a line like this:

$variables['node'] = $variables['elements']['#node'];

and after it modify $variables['node'] as you see fit.
Use Computed Field to create a field that shows author's name, and in case of anonymous authors displays arbitrary text. Turn off displaying author and use this field instead.


View AJAX Refresh causing multiple refreshes In attempting an AJAX refresh on several views contained in separate blocks on a single page, I seem to be coming across a problem. This is running on D7.34

The idea is for the page to contain 4 blocks, each with a view sorting by random - then using a simple click() on the block title to
activate a refresh of any given view allowing the user to view a new random item.  I am using the common:

var selector = '.view-dom-id-' + dom_id;
jQuery(selector).triggerHandler('RefreshView');

to achieve this, which works perfectly.  The trouble I am having is in increasing multiples of refreshes:

clicking on one view refresh does refresh the view, but it seems to create a counter, when a different view
is refreshed, that second view refreshes twice. Then going back to the first, the view would refresh 3 times, and so on.
It doesn't happen if clicking on the same view multiple times - in this case it only refreshes once as expected, it only
occurs when switching between refreshing different views, however it continues to "count" these refreshes which then effect
the number of times a different view is refreshed when the other refresh is triggered.

I have confirmed that the selector is correct and obtains the unique dom_id for that view
I have confirmed that the call jQuery(selector).triggerHandler('RefreshView'); only occurs once per click
this occurs in Drupal.Behaviours, drupal_add_js, and straight JS added to a tpl file - they all "work" but with the same refresh issue
I have used once() in the call as well with no perceived effect

It seems like when the triggerHandler triggers the refresh, the view itself is refreshing multiple times for reasons I can't seem to
figure out.  I have tried dozens of permutations now without any change in behaviour.  I can't post of all the code from my attempts, but here
is the last attempt which "works" but still refreshes multiple times - this is a straight JS addition to page.tpl, layed out for easier reading:

<script>
  jQuery(document).ready(function()
  {
    jQuery('#block-views-random-cat-block h2').click(function()
    {
      jQuery.each(Drupal.views.instances, function(i, view)
      {
        if (view.settings.view_name == "random_cat")
        {
          var selector = '.view-dom-id-' + view.settings.view_dom_id;
          jQuery(selector).triggerHandler('RefreshView');
        }
      });
    });

    jQuery('#block-views-random-dog-block h2').click(function()
    {
      jQuery.each(Drupal.views.instances, function(i, view)
      {
        if (view.settings.view_name == "random_dog")
        {
          var selector = '.view-dom-id-' + view.settings.view_dom_id;
          jQuery(selector).triggerHandler('RefreshView');
        }
      });
    });
  });
</script>

If I limit the page to one view only, it seems to work fine - it's only in the fact that there are multiple views that I see this effect.

This is not really an answer, but I put it here so I could format my code.

This seems to me like it may be a bug.

I have been playing around with this for about an hour and a half now and could not get it to work as expected when I had more than 1 view on a single page.

To test I made a view called 'testing' with 2 blocks with the names 'block_1' and 'block_2'. I placed both of these blocks on a single page and added the code below to refresh them via ajax when clicking the heading.

code:

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

      jQuery.each(Drupal.views.instances, function(domid, view){

        if(view.settings.view_name == 'testing' && view.settings.view_display_id == 'block_1' ||
           view.settings.view_name == 'testing' && view.settings.view_display_id == 'block_2') {

          jQuery('#block-views-'+view.settings.view_name+'-'+view.settings.view_display_id.replace('_', '-')+' h2', context).once().click(function(){
            jQuery(view.element_settings.selector).triggerHandler('RefreshView');
          });
        }
      });
    }
  };

})(jQuery);

This ended up with the same behavior as the OP.

I think you should file a issue report in the views module issue queue


Drupal files on NFS, performance degredation Many people use NFS to keep the sites/default/files directory outside of the normal webroot of a Drupal install.

However, I'm running the entire Drupal install over NFS.

When the site has not been accessed in some time, there's a solid 15-20 seconds of delay before a page loads. After that everything is fine. I have Drupal's page caching turned off for these tests to provide consistent results.

Initially I found that PHP's realpath_cache needed to be adjusted, because the default of 16k is not enough to handle all of paths Drupal loads when bootstrapping. I have this raised to 128k, and I see now that the utilized cache size goes up to around 40-50kb (after browsing around the site all over to "trigger" more file loads).

However, that does not seem to affect performance at all. Those cache entries expire anyway and will eventually PHP will need to hit the FS again.

I also have the built in "poor mans cron" disabled, so it's not related to Drupal running a bunch of cron tasks on that page load.

I suspect it may be related to NFS.

Is anyone else running a Drupal install completely over NFS, or have you in the past and come to any conclusions that may help?

Assuming APC is installed; inside php.ini

; http://www.php.net/manual/en/ini.core.php#ini.sect.performance
realpath_cache_size=1M ; 1MB
realpath_cache_ttl=3600 ; 1 hour

; APC
; http://www.php.net/manual/en/apc.configuration.php
apc.ttl=2419200 ; 4 weeks
apc.localcache = 1
apc.localcache.size = 1024
apc.num_files_hint = 2048
apc.user_entries_hint = 128

apc.file_update_protection = 10
apc.stat = 0
apc.stat_ctime = 0
apc.file_md5 = 1

; OPcache
; http://www.php.net/manual/en/opcache.configuration.php
opcache.enable_file_override = 1
opcache.validate_timestamps = 0

Then when your code changes you need to restart Apache or run

apc_clear_cache('opcode');
opcache_reset();

And for Drupal install the following modules as these are designed to help with the drupal files dir when used on a NFS filesystem
https://drupal.org/project/imageinfo_cache
https://drupal.org/project/advagg
https://drupal.org/project/httprl (will speed up the above 2 modules)