“Create new account” Block in drupal I am working on a Drupal project where I require a "Create new account" form on a content page. Can anybody help me out with this? Is there any module or any alternative to get "Create new account" as a block?

Use this module http://drupal.org/project/formblock

Download and install the module. Navigate to admin/structure/block You can see Registration form as a block and choose the region to appear.

User Registration to appear in a block taken from this source.


Avoiding entity-type errors on module installation I created a logger service that uses a config entity for configuration: https://drupal.org/project/dblog_persistent

Unfortunately, it appears that this module is not installable on a new site, because Drupal attempts to instantiate the logger service before actually installing the config entity type it depends on - the result is a PluginNotFoundException.

There has to be some way to prevent services from being instantiated until the module is installed, or not?

This is the class and constructor definition:

<?php

namespace Drupal\dblog_persistent\Logger;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\dblog\Logger\DbLog;
use Drupal\dblog_persistent\DbLogPersistentStorageInterface;

/**
 * Class DbLogPersistent
 *
 * @package Drupal\dblog_persistent\Logger
 */
class DbLogPersistent extends DbLog {

  /**
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
   */
  protected $channelStorage;

  /**
   * @var \Drupal\dblog_persistent\DbLogPersistentStorageInterface
   */
  private $storage;

  /**
   * @var \Drupal\dblog_persistent\Entity\ChannelInterface[]
   */
  private $channels;

  public function __construct(Connection $connection,
                              LogMessageParserInterface $parser,
                              EntityTypeManagerInterface $manager,
                              DbLogPersistentStorageInterface $storage) {
    parent::__construct($connection, $parser);
    // The following causes an error on installation:
    $this->channelStorage = $manager->getStorage('dblog_persistent_channel');
    $this->storage = $storage;
  }

And the service definition:

services:
  dblog_persistent.storage:
    class: Drupal\dblog_persistent\DbLogPersistentStorage
    arguments:
      - '@database'
  logger.dblog_persistent:
    class: Drupal\dblog_persistent\Logger\DbLogPersistent
    arguments:
      - '@database'
      - '@logger.log_message_parser'
      - '@entity_type.manager'
      - '@dblog_persistent.storage'
    tags:
      - { name: logger }

As a hack, I could surround every function in the logger with ifs that ensure it doesn't run unless installation is complete, but that's pretty dirty. Is there at least some kind of null entity storage that the constructor could fall back on, to minimize the amount of defensive programming?

I've revised my approach here several times, but so far the cleanest solution in my opinion is:

Store the entity_type.manager service, not the storage. When the storage is used, place the whole chain $this->manager->getStorage()->loadMultiple() into a try/catch.

This avoids having to handle the special case in two places: Once in the constructor (when acquiring the storage might fail), and again in the loading function (when the storage might not exist, because it failed in the constructor).

<?php

namespace Drupal\dblog_persistent\Logger;

use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\dblog\Logger\DbLog;
use Drupal\dblog_persistent\DbLogPersistentStorageInterface;

/**
 * Class DbLogPersistent
 *
 * @package Drupal\dblog_persistent\Logger
 */
class DbLogPersistent extends DbLog {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $manager;

  /**
   * @var \Drupal\dblog_persistent\DbLogPersistentStorageInterface
   */
  protected $storage;

  /**
   * @var \Drupal\dblog_persistent\Entity\ChannelInterface[]
   */
  private $channels;

  public function __construct(Connection $connection,
                              LogMessageParserInterface $parser,
                              EntityTypeManagerInterface $manager,
                              DbLogPersistentStorageInterface $storage) {
    parent::__construct($connection, $parser);
    $this->manager = $manager;
    $this->storage = $storage;
  }

  protected function getChannels() {
    if ($this->channels === NULL) {
      try {
        $this->channels = $this->manager
          ->getStorage('dblog_persistent_channel')
          ->loadMultiple();
      }
      catch (PluginNotFoundException $e) {
        $this->channels = [];
      }
    }
    return $this->channels;
  }
}


How was this amazing drupal performance presentation done? How was this amazing drupal performance presentation ( http://rupl.github.com/high-performance-theming ) was done? Which jQ libraries are needed? And what is the best place to ask?

Thanks

Amnon

It's nothing overly complicated; the 3d navigation makes use of the reveal.js library.

  reveal.js is a framework for easily creating beautiful presentations using HTML.

And then there are a few helper libraries:

Highlight.js - for syntax highlighting
classList.js - adds element.classList support to browsers that don't support it
carousel.js - seems to be custom DOM helper functions.

Reveal is pretty easy to use, it just requires a lot of patience and a will to succeed. Good luck!


Use image field in an entity query condition How to use image field in a condition of an entity query?

To get X nodes which have no image as value of field_image I've tried this:

$nids = \Drupal::entityQuery('node')
->condition('type','X')
->condition('field_image',NULL , '=')
->execute();

it doesn't work I got always empty result.

You could try:
$query->notExists('field_image');


How to get $form_state['values'] after a drupal_get_form() call? I have an form in a block with ajax submission. The block view code calls drupal_get_form, adds some other info, uses a custom theme tpl to create the block.

I want to replace the form in the block with a thank you message after successful submission.

AJAX works: The ajax on the submit element of the form means that a custom ajax callback  can replace the entire form with another themed chunk, passing in the form values received by the form so they can be merged in the thank you template. This works well because the ajax function has access to the form_state.

But what if AJAX is unavailable on the client? Then the normal form submit happens and the block view function just gets a blank form.

So how can my block view function get hold of the submitted values to feed them into the thank you template?

Edit: messy work-arounds

I could just access $_POST but that's nasty and unvalidated! yuk
In the submit handler I can copy the $form_state['values'] variable to a superglobal, and check for that.

I realise this is an old question but: drupal_get_form() is mostly a wrapper for drupal_build_form(), and (the docs say) is intended to be used "instead of drupal_build_form() when $form_state is not needed", with the implication that if $form_state is needed, it's OK to go straight to drupal_build_form().

The only extra bit drupal_get_form does is assemble a 'build_info' array in the $form_state, so instead of (e.g.) $block['content']['form'] = drupal_get_form('myform_name', $arg);, you could do something like this:

  $form_state = array();
  $form_state['build_info']['args'][] = $arg;
  $block['content']['form'] = drupal_build_form('myform_name', $form_state);

You should find your $form_state variable is now populated as it would be if you were operating inside the form building function, including any $form_state['values'] or $form_state['input'] in the event that your form is being rebuilt.


Reading textarea values per row: what is the internal method? If I'd like to create a textarea field for a admin configuration form that would include different configurations on multiple rows then how can I read these values/rows?

I know there must be a internal method for this since it is very common form field/input type. I just wouldn't like to invent it again.

And I just ran into a module that was using this same principal but it matched the rows with regex \n\r which turned into few gray hairs if you had only one value since it didn't then match if you didn't deliberately press enter. And for clarity it obviously didn't check that if the first line included text, just that regex and therefore no settings were saved.

That was also a wake up for that there must be some more intelligent and elegant way...

Drupal doesn't provide a method for that.

Just use whatever PHP splitting method makes sense for your use case. A very simple example might be:

$text = str_replace(array("\r\n", "\r"), "\n", $text);
$vals = explode("\n", $text);


Folder and file sharing in Drupal Here is what I am trying to achieve.
I have two roles Teachers and Students.

Each teacher has images of answers written by the students in an exam. After checking these papers, teacher takes an image of each answer-sheet. He names it in a certain pattern using student-id. Thus, teacher has many images (like sid-1-im1.jpg, sid-1-im2.jpg, sid-2-im1.jpg). A student can have multiple images on his name depending on how many sheets he had submitted.

I want to create a website where a teacher can create a folder for this exam, say, Economics-2017-2018. Within this folder, he can upload all images.
What would be the best way to achive this folder+multi-file upload?

Next I want to programmatically assign permissions to these uploaded images based on student id of the file name. So that, a student can view only his files.

How can this programmatic feature be achieved.

There are more features such as notifying students, ability to comment on files etc. But, I think drupal can handle them easily.

I intend to use Drupal 7 or 8 for the purpose.

You wouldn't actually need to write any custom code to implement something like this.

A possible solution is outlined below. It is aimed at Drupal 7. Some of the functionality mentioned may not be ready for Drupal 8 so you might need alternate modules or custom code in those cases.

Create a new content type, which would be named "Exam paper" or similar. There would be one node per student per exam.
Add a multiple value file field to the content type. Make sure it uses the private file system. Using the private file system will mean that only users with access to the node will be able to access the files attached to the node.
You can use the file field paths and token modules to make it so that the file directory structure and file names match the pattern you want. With the tokens you can easily reference student, teacher or exam information from fields on the node in the path or file name. This has no effect on access control but might make things better for you in other ways.
There are a number of ways you can handle access control as there are a variety of access control modules available for nodes, however I would be inclined to go with the node access user reference module. So you would add an entity reference field on the content type that references users with the student role. You can then set permissions so that the referenced user can access the node and other users cannot.
You can use the rules module to notify the user under various circumstances.
You can use Drupal core comments to have comments on exam paper nodes.
Due to using nodes you can leverage the wide variety of add on modules that focus primarily on nodes.
If you want to store additional data with each specific file, you can install the file entity module, which will allow you to add fields at the file level as well as the node level.


how to create image upload of difference dimensions I am creating a custom gallery. I require images that are the thumb nail and the big image size. I have custom content type. When i add the image field it allows me to enter the dimensions size. Is there a way for drupal to create 2 images. ie thumb and big image

You can either create two image fields, one for the media image and another one for the thumb, or you could just have one and use different Image Styles ( admin/config/media/image-styles in Drupal 7 ) for both the full and thumbnail. You could even add Image Javascript Crop for more fine-grained control of the thumbnail.


views and contextual filters with entity reference field how do you use contextual filters to a views block when you want to use a reference field from the content type displaying the view?

here's the simple scenario

artist content type has some basic fields
song content type has a reference field referencing which artist
event content type has a reference field referencing which artist is headlining
view has a block with fields

on each Artist content page, it's working and i have a block of songs for that artist in the sidebar. i used views provide default entity and basic validation (but does not work for below)

on each Event content page, i want a block of songs for that artist in the sidebar. Essentially i want the reference field in the event to match up with the artist's songs.

since we don't have access to the path, i've been playing around with contextual filters on the reference field (and reverse of it) to no avail.

Ok thanks to @Jimajamma I seem to have figured it out, it's actually quite simple.

In order to get the argument into the Song view, you add a 'contextual filter' and select the Song's artist reference field. Then under 'When the filter value is NOT available' choose 'provide default value' and PHP Code. In that PHP code you want to return the value of the Event's artist reference field like so

$node=menu_get_object();
return $node->field_event_artistref['und'][0]['target_id'];

then under 'When the filter value IS available or a default is provided', choose 'Specify validation criteria' and basic validation

In a nutshell, this is simply taking the argument of the artist the Song references and comparing it to the default value you provided which is the current node's artist reference field. also as @Jimajamma said, best practice would be to use a switch statement on the node->type to be able to use the songs by %artist block on several different types of content like artist nodes.

In the contextual filter, you can use php to supply the argument.  There, you could put in something like:

$node=menu_get_object();
return $node->field_headliner[0]['nid'];

where field_headliner is the node reference field of your event content type.  The exact syntax above is D6, but I am pretty sure it's the same or at least very similar in D7.

Then, just as long as this view block is being show in/on an event page, the above will return the nid of the headlining band, and if your view is set up to filter on that node nid, you should be set.

You could even get fancy up in there with something like:

$node=menu_get_object();

switch ($node->type) {
  case 'band':
    return $node->nid;
  case 'event':
    return $node->field_headliner[0]['nid'];
  default:
    return 0; // or however you want to return an error
}

and then the same view block display could be used on both types of page.  Then just put this block on band and event pages and you should be all set.


Using the jQuery Update module throws the "F is undefined" error I am using the jQuery validate module (which is mandatory for client side validation module).

If I use that module, my existing functionality is not working well. It is throwing, "F is undefined" while using minified version or, "$.ui is not a function" with the normal version of jQuery.

I understood that version plays the problem here. How do I avoid the error message?

I use jQuery Update on every site we make.

One typical problem it has, is that it can cause problems on admin pages.  The issues for the module has a patch (http://drupal.org/node/775924#comment-3010750) that fixes the problem.  You can also edit this to use any version of jQuery you want, as long as you place the proper versions in the module folder.


Adding DIV ID= Tags to a views table output I know that I can do a template override to style the views output, as described here.

I've also used a template preprocess function to add a "row_classes" to a views output. This will add DIV classes, but is it possible to add IDs as well?

Could I also use the views UI for that, maybe with a rewrite?

Btw, I ended up using a rewrite in the views UI.
I added "content:nid" to the top of the fields and then used "rewrite content" on the title field to:

[title]

Not a perfect solution but it seemed practical to me (at least at the time of writing this) ;-)


Why isn't the #ajax property available for more Form API elements? Looking at https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x because I haven't seen a page updated for Drupal 8, it seems like only a select few form elements are allowed to have #ajax on them.  Isn't this too limiting?  I want to do Ajax on a markup element.  There are a lot of scenarios in which I would want to do Ajax with my own custom HTML, but I don't want to lose the functionality of the Form API, like getting the $form and $form_state.

The way I see it, there are two ways of doing Ajax in Drupal, either normally by just calling a controller, or by using an element in the Form API with an Ajax callback.  If I do Ajax normally, I can create data in Javascript however I want and send it to php, but I can't get the data in Drupal's $form object or call some of Drupal's special Ajax functions like entity autocomplete.  If I use the Form API, I lose the ability to respond to any events on certain elements of the form.

Why is it like this? And, is there a way to get around it without modifying core?

In Drupal 8 render elements are plugins and you can define a custom render element in a module without modifying core.

The scenarios you describe probably don't need a custom render element. A #markup with an event attached to it is like a link or a button, where you remove the styling with css.

Additionally you can hook into ajax js and react on events with your own javascript. See ajax.js, the hooks are called prototypes.


How do you resize a form element in a block? I have two blocks, one with a search forum(using drupal finder module) and an email invite module, and for some reason both input forms go outside the blocks borders.

Both are giving me two different problems.  The finder module's search bar is going beyond the block borders but the entire email invite block is outside the borders.

How do you adjust the size of blocks?

Set the #size and #cols (textarea) attributes of the different form elements as appropriate. You can do that with a hook_form_alter() implementation if they're not your forms.

Additionally, you can also use CSS, using the #attributes property.


How can I programatically enable a block by default for a theme? I have set up my site to allow users to set a different theme for each node, which works fine. Some of my themes make use of blocks, so I created a custom blocks module added them programatically, which works fine. The problem comes when I need to enable them. When a user creates a new node, all of the themes are available but none of the blocks are enabled. I have to go in and enable each block manually for each theme on each node. Is there any way to basically programatically say "when this theme is enabled, enable this block in this region" so I don't have to manually enable each block?

Please note that I am using Drupal 6 and upgrading is not gonna happen any time within the next couple of months.

There isn't a way to perform programatic actions during the enabling of a theme. You can, however, have your custom blocks module add an entry to the database for the placement of the block into a theme's region, before that theme is enabled.

To do that, you would implement a database insert query, perhaps in your module's install function, that creates an entry in the blocks table for the block(s) in certain regions in any theme. You can create these entries whether the theme(s) are enabled or not.

The result will be that the block appears to be enabled when the theme is installed.

Here is a d.o forum post on the subject, with some helpful examples


How do I output view (page display) content in page--.tpl.php? I have a view called sabk__view whose path is /sabk. It has a page display mode. I created a page named page--sabk.tpl.php in order to display the content of view, but I don't know what code displays the content of view.

I also checked modules/system/page.tpl.php to see if there is any useful variable (e.g. print render($content)), but none of them displayed anything about view.

How can I display view's output in a specific <div> tag? Do I need to implement <theme>_preprocess_node?

I am using Drupal 7, if that makes any difference.

I use the following function to solve the issue

print views_embed_view('NAME_OF_VIEW','page');


Custom login block that redirects to password protected page that is not published otherwise I realize that there are many ways and modules to accomplish this with, but this is the one particular way I need it and I'm having trouble finding a good solution. So here is what I'd like to achieve:

A custom block on a page with username and password fields. After entering the right combination (it'll be just one pair probably), the form would redirect the visitor to a content page that is unpublished.

Logged in visitors should not be Drupal users, nor should they go through a registration process. Certain people will know the right user/pass combo and only they should be able to access the protected page.

The Protected Pages module doesn't create a login block, password input only possible on the actual page that is protected.

I tought about creating a custom module with a form that would redirect after entering the right user/pass combo, but if the destination node is unpublished, it won't work anyway.

Do you have any good ideas for this one?

Thank you,
Bálint

Giving users permission to view unpublished content could potentially be a security risk, and it's not (easily) possible to restrict it to just viewing a particular content type.

Why not publish the node, but only allow users with a certain role be able to view them using the Content Access module.

Then create a few accounts with this role, setting the usernames and passwords yourself.

Then just use the standard Drupal login form but then alter the redirect once logged in with hook_user_login:

function hook_user_login(&$edit, $account) {
    if (in_array('your_role', $account->roles)) {
        $edit['redirect'] = 'node/123';
    }
}

By creating the accounts this way it means you can use the main Drupal authentication system so reducing the amount of work that you need to do...


How to improve Drupal speed when developing in localhost I'm looking for tips from other Drupal developers to make Drupal faster when developing (specially Drupal 7)

Taking in consideration that during development you don't want cache, so you can see the result of changes in code php/css/js. (See some answers here to flush cache / disable cache permanently)

Googling for "drupal slow localhost" will give some tips... but I want yours :)

The best tip you can use (this really change my life) is adding a line in your my.cnf file:

innodb_flush_log_at_trx_commit = 0

You can find this file in your wamp folder or if your on linux server: /etc/mysql/my.cnf

Regards


Page template for custom form I'm trying to create a new page template for a custom form I'm building in my module. My goal is to use create something like a new page.tpl.php for this specific form and it looks like this method is creating the equivalent of a custom node.tpl.php within the content area of my site instead of generating a separate page template.

For example

/*
 * Implements hook_menu
 */
function mymodule_menu() {
  $items = array();
  $items['foo/my_custom_form'] = array(
    'title' => 'My custom form',
    'page callback' => 'mymodule_custom_page',
    'access callback' => TRUE, // Everyone has access.
  );
  return $items;
}

function mymodule_custom_page(){
  return theme('mymodule_template');
  return drupal_get_form('mymodule_form');
}

/*
 * Implements Hook_theme
 */
function mymodule_theme() {
  return array(
    'mymodule_template' => array(
      'template' => 'custompage', // template file called custompage.tpl.php
      'arguments' => array(),
    ),
  );
}

function mymodule_form($node, &$form_state){
//my form in here
}

I'm having an issue with the form not appearing.

Maybe I'm going down the wrong path and should be trying to create function in my theme's template.php, and then use a hook_preprocess_page to set some variables to create a page--custom.tpl.php for my form?

I can achieve what I'm trying to do by making some configuration changes to some blocks and redrawing the content area with CSS, but not sure if that's the best practice.

Here is your issue, your can't return twice in a function.

function mymodule_custom_page(){
  return theme('mymodule_template');
  return drupal_get_form('mymodule_form');
}

What you need to do is just the first line,  return theme('mymodule_template'); You also need to change your form function parameters to &$form, &$form_state.

Then, in your custompage.tpl.php, you do the drupal_get_form('mymodule_form');

Result:

/*
* Implements hook_menu
*/

function mymodule_menu() {
  $items = array();
  $items['foo/my_custom_form'] = array(
    'title' => 'My custom form',
    'page callback' => 'mymodule_custom_page',
    'access callback' => TRUE, // Everyone has access.
  );
  return $items;
}

function mymodule_custom_page(){
  return theme('mymodule_template');
}

/*
* Implements Hook_theme
*/

function mymodule_theme() {
  return array(
    'mymodule_template' => array(
      'template' => 'custompage', // template file called custompage.tpl.php
      'arguments' => array(),
    ),
  );
}

function mymodule_form(&$form, &$form_state){
  //my form in here
}

And in custompage.tpl.php:

print drupal_get_form('mymodule_form');


How can I get lat/lon from an address? I have these modules

addressfield
geofield
geocoder

Is there any function to which I can pass an address like Stree, zipcode city, Country and it returns a lat/lon from that address?

I have searched in the code of geofield and geocoder but unable to find any helper function.

Using google geocoding with geocoder module, you may use another geocoding provider, i think this requires a google map token now given google's new rules :

// @return Geometry Returns a geoPHP geometry object. Generally a Point.
$point = geocoder('google', $address);
$lat = $point->coords[1];
$lon = $point->coords[0];

I did this long time ago, please check.


How to display a node's last saved date? Drupal 8 already displays the last saved date in page edit form. I want to add a field to a node that displays it again. I am using hook_form_alter() and doing this in my module, but it displays the current date.

  if ($form_id == 'node_page_edit_form') {
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => t('Changed date'),
      '#weight' => -1,
      '#markup' => format_date(time(), $created),
    );
  }

How do I display the last saved date?

The arguments you are passing a format_date() are wrong: The second argument is the format used for the date, not another timestamp.

You should code similar to the following one.

  if ($form_id == 'node_page_edit_form') {
    $node = $form_state->getFormObject()->getEntity();
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => t('Changed date'),
      '#weight' => -1,
      '#markup' => format_date($node->getChangedTime(), 'medium'),
    );
  }

Even better, you should use the service Drupal provides for formatting dates.

  if ($form_id == 'node_page_edit_form') {
    $node = $form_state->getFormObject()->getEntity();
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => new \Drupal\Core\StringTranslation\TranslatableMarkup('Changed date'),
      '#weight' => -1,
      '#markup' => \Drupal::service('date.formatter')->format($node->getChangedTime(), 'medium'),
    );
  }

Instead of 'medium', you can use the default value, or another one you prefer.


Date field Start and End limit When we create a date field in node form, we can set START and END years to be shown in that date field.
If we are creating a date field programatcaly, how do we do that?

I have a date field, my_date, I want to to show only next 5 years from now on.
Any help?

$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
);

I tried to see structure bu creating a date field and printing the form, but found nothing.

We can do it like this...

$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
  '#after_build' => array("custom_range_date")
);

using '#after_build' => array("custom_range_date")

function custom_range_date($form_element, &$form_state){
    // We unset the current values
    unset($form_element['year']['#options']);

    // Now we set the range we want
    $max_age = date('Y') - 100; // 100 years ago
    $min_age = date('Y') - 7; // 7 years ago

    // Now we populate the array
    $form_element['year']['#options'] = array();
    foreach (range($max_age, $min_age) as $year){
        $form_element['year']['#options'][$year] = $year;
    }

    // We return our modified element
    return $form_element;
}

SEE: https://www.drupal.org/node/1165138


hook_field_views_data() not picked up in mymodule.views.inc I have implemented hook_field_views_data() in mymodule.views.inc but the hook is not picked up.

In mymodule.module I have the following code to define where mymodule.views.inc resides.

/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule') . '/views',
  );
}

Below is the code for views/mymodule.views.inc. And the problem is that if I try dumping out $field for example it seems like hook_field_views_data() is not picked up.

I tried to change mymodule_field_views_data() to mymodule_views_data, and that function is picked up. I tried this just to be sure that the file is included at all.

/**
 * Implements hook_field_views_data().
 */
function mymodule_field_views_data($field) {
  $data = field_views_field_default_views_data($field);

  // Add a handler for localities.
  foreach ($field['storage']['details']['sql'] as $type => $tables) {
    foreach ($tables as $table_name => $columns) {
      if (!isset($columns['locality'])) {
        continue;
      }

      $column_real_name = $columns['locality'];
      if (!isset($data[$table_name][$column_real_name]['filter'])) {
        continue;
      }

      $data[$table_name][$column_real_name]['filter']['handler'] = 'mymodule_views_handler_filter_locality';
    }
  }

  return $data;
}

mymodule.info

name = mymodule
description = Bla bla
core = 7.x

files[] = views/mymodule_views_handler_filter_locality.inc

That appears to be the correct behaviour.

If you look at the code for field_views_data():

function field_views_data() {
  $data = array();
  foreach (field_info_fields() as $field) {
    if ($field['storage']['type'] != 'field_sql_storage') {
      continue;
    }

    $module = $field['module'];
    $result = (array) module_invoke($module, 'field_views_data', $field);

    if (empty($result)) {
      $result = field_views_field_default_views_data($field);
    }
    drupal_alter('field_views_data', $result, $field, $module);

    if (is_array($result)) {
      $data = drupal_array_merge_deep($result, $data);
    }
  }

  return $data;
}

You can see it only invokes hook_field_views_data() for the module that defines the field. So in the case of (what looks like) an addressfield, the function Views will call has to be called addressfield_field_views_data().

It's more likely you're looking for hook_field_views_data_alter() which will allow you to alter existing definitions.

But if that doesn't do what you need, you might have to actually define the addressfield_field_views_data() function yourself on behalf of addressfield (if it's not already implemented somewhere). Should be a pretty quick test to find out.


Insert 'select all' choice in a particular level in Taxonomy Term Reference Tree Widget I'm using D7. And I have a big term reference tree with Term Reference Tree. There are so many terms in the tree that I'd like to put 'select all' choice in it for usability.
Is it possible to put 'select all' choice in some level?

Let me show you the example of what I want to do below...

(Ex)
Let's say there is a vocabulary whose name is 'Food'

[Food]
-Vegetable
--Select All
--Pumpkin
--Carrot
--Radish
--Potato
-Fruit
-Fish

So, what I want to do is...if you check the 'Select All' under the Vegetable level, the all of choices(Pumpkin, Carrot, Radish, Potato) will be checked.

I searched the way to do that but couldn't find the answer. Any tips would be appreciated. Thank you.

Added:
I found you can do something like I want to do by the setting below...
-Start minimized =>Whichever
-Leaves only =>Off
-Select parents automatically =>On
-Cascading selection =>On

With the setting above, you can chose all choices by checking the parent level.
But, I also wanted to enforce users to chose the deepest level.
With the setting above, users don't always have to chose the deepest level...
So, correctly, I'd like to say I want to put 'select all' and enforce users chose the deepest level.
I still need your help. Thank you.

Drupal have Taxonomy Manager module where all levels and terms have checkbox options and also add, edit, delete, move, functionality here.
Taxonomy Manager:

This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.
For using the Taxonomy Manager you should have JavaScript and automatically load of images enabled in your browser.


Change taxonomy list automatically generated paths I made a dummy second hand car website, for which I made a taxonomy list "Popular brands". I've added this list to the front page, but each of the respective links (e.g. each brand) links to popular-brands/[brand] instead of brand/[brand], how I'd like it to be.

The first is generated automatically upon creating this block view. Can I alter this path to become the latter?

The case can be seen live at ikhoefgeen.be (site is in Dutch by default, I'm not sure wether or not it automatically displays in English).

Are you using pathauto?

Check patterns at admin/config/search/path/patterns and then update URL aliases


How to restrict access to page by URL depending on which page you came from I have page which implements by hook_menu and i want to permit access for this page if user come from certain form but not from just url string. How can i solve it? Thanks.

depending on which page you came from

per se is impossible, because people can easily forge their referer header. What you need to do in your specific, form related situation is to:

In form submit handler, set session variable, like $_SESSION['acces_valid_to'] = time() + 3600 - this will store time one hour into future for specific user.
In access hook, for example hook_node_access if we are talking about nodes, test if this variable is set, and if it is still valid. If not, send 403 Forbidden.
If you want, you can unset it after any page view, that will make sure your user will view his page only once.

If you will have specific problems with any of these steps, ask next, more specific question.


Views format: faster fields or rendered entity? I'm building some views that returns many content types that have different fields, so I'm choosing to display results as "rendered entity" instead of "Fields".
I would like to know if there are perfomance reasons to use fields or rendered entity.

If you are able to cache the views output, you should not need to think about that problem. If it is not cachable:

I would say rendered entity will cause more overhead due to rendering each field of the content you selected while with fields you could limit it to the needed fields. If rendered entity and fields equal, I would go for rendered entity with display suite.

For actual performance benchmarking try using apache's benchmarking tool for both solutions.

ab -n100 -c1 http://domain.tld/path/to/view

remember to disable caches while running the tests.


Drupal Commerce Change Order Weight at Checkout I am using Commerce FedEx to retrieve quotes at checkout and using a SmartPost setting that requires packages to be over 1lb. to return a quote from FedEx. I need to have the order shipping weight from Commerce Physical Products default to 1lb. for the entire order weight if the order weight is under 1lb. at the time of checkout. I do not want to make all of the products a minimum of 1lb. due to inaccurate quotes if multiple items are ordered so I am looking into a solution with Rules, but cannot seem to get an Action that will allow me to do this.

Example: One product is 0.25lbs. When two are ordered, the shipping weight should be 1lb. at checkout to receive a quote. When six are ordered, the shipping weight should be 1.5lbs.

You can use HOOK_commerce_fedex_rate_request_alter(&$request, $order) to alter the request before it goes out:
function MYMODULE_commerce_fedex_rate_request_alter(&$request, $order) {
    // Test this value and set it to whatever you'd like.
    $request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Value'] = 1;
    $request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Units'] = 'LBS';
}

Just test the value and update it if you want.


Sort by substring in views? I have a content type with a full person's name in the title, in the format "John Smith". I want to have a view that sorts this content by last name. I've looked at the views interface but I don't see a way to get a substring. (I understand that this won't work perfectly but for our data set, it will work well enough.)

Will I have to add a field of the last name to the content type? Or is there a way I can get views to sort by a substring?

Adding a new field for the last name will be the easiest way. Sorting by a substring would mean that you also have to cover the possibility of spaces in first names and/or last names.


How to use "user logged in" as an access argument for a MENU_CALLBACK? I would like to require that users be logged in to access a particular MENU_CALLBACK.

The following works, but only for the admin account.  Regular users are still denied access:

'access arguments' => array('user_is_logged_in')

There must be an access argument that just checks for authenticated users?

access arguments is for the arguments that will be passed to the callback function...you need to use access callback instead:

'access callback' => 'user_is_logged_in'

Since user_is_logged_in() doesn't take any arguments, you can safely remove access arguments for your menu item.

Your current code works for the admin account only because the default access callback is user_access(), which bypasses the access check for user 1.


Programmatically create a comment form for a node I'm trying to port a theme from Drupal 6 to Drupal 8, and I find code like the following.

$edit = array();
$edit['nid'] = $node->nid;
$form = drupal_get_form('comment_form', $edit));

How do I load the form in Drupal 8? I get the following error:

  Fatal error: Call to a member function getEntityTypeId() on null in /www/site/core/lib/Drupal/Core/Entity/EntityForm.php on line 77

The line causing the error is the following one:

\Drupal::formBuilder()->getForm('Drupal\comment\CommentForm');

I can't work out how to pass the node object to the form builder. How can I do it?

FormBuilder::getForm() doesn't accept just an argument; after the first, the other arguments are:

  Any additional arguments are passed on to the functions called by \Drupal::formBuilder()->getForm(), including the unique form constructor function. For example, the node_edit form requires that a node object is passed in here when it is called. These are available to implementations of hook_form_alter() and hook_form_FORM_ID_alter() as the array $form_state->getBuildInfo()['args'].

So, \Drupal::formBuilder()->getForm('Drupal\comment\CommentForm', $node); would be perfectly fine. It's up to the form builder, using those arguments.


How do I create a Rule "When role is removed, send email to the user"? I am trying to create a rule that sends an email to the user when a role has been removed from their account. I can't seem to find a rule reaction under User "When role is removed". How do I create a rule to do this?

It has to be triggered when a particular role ("subscriber") has been removed. So we can use 2 conditions User has role(s), to check if he had the role before the edit, and that he doesn't have it after the edit :

1st condition : selector "account_unchanged", check the role "subscriber" (here test)

2nd condition : selector "account", check the same role, and negate.


How can I set a placeholder variable in page.tpl.php from a page callback? I have a value in page.tpl.php that I would like to set in page callbacks, independently from the main content.

In page.tpl.php:

<?php print $placeholder ?>

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

What I would like to do in the page callback:

function my_module_page_callback_foo() {
  $placeholder = 'foo';
  return 'Page Content';
}

Obviously, that isn't going to get me very far.

I'm hesitant to use hook_preprocess_page because then I'll have unnecessary conditional logic to determine what the menu item is (won't I?). Is there another, 'drupal way' of doing this?

I'm coming from a more 'Zend-y' world where I have access to my view and my layout variables from the controller.

There are a few possibilities, not sure which one would work best for you. There isn't a really easy way to do that.

I would say the "drupal way" of doing that would be to expose your additional content as a block. You can configure that to only show up on specific pages and place it above the main content.

There is also hook_page_alter(), but that requires the same conditonal checks as a template_preprocess.

You could also return a render array in your page callback and then display it separately in your page.tpl.php, something like render($page['content']['system_main']['part_a']) and so on. You could do that only in a template suggestion for a specific page, like page--yourpath.tpl.php.

To avoid messing with page.tpl.php too much, there is also the possibility of overriding the so called 'delivery_callback' (see menu_execute_active_handler() in your menu router item for that page. The default delivery callback is drupal_deliver_html_page().


Views Group by date plus showing newest node I have a view of photo nodes uploaded by users and want to group them by post date and user.
That part is pretty straightforward once you patch views. Just set sort by "post date" with "day" granularity and add a username field to group by user and day.

I use "count distinct" for nid to show the number of photos by user. I even used "format plural", "no results behavior" and "rewrite output" to only show a link to more photos if there are more than 1 photos per user. So far so good ...

The challenge I'm having is when I try to show a photo and title. When I add the "title" field with "group results" it's now showing each photo instead of grouping. If I use "max" or "min" it will only show 1 photo per user but now the photo won't match the title.

So, how can I show a photo and matching title for photos grouped by day and user?  At this point it doesn't matter much if the photo is the oldest or newest for that user and day.

thanks!

In terms of the database there is two ways to make this happen.

Using GROUP BY (=aggregation)

group by user and day.
add additional sort criteria so that the photo you want to display is the first in this ordering.
mysql automatically displays the value of the first row in the group for each field that hasn't another aggregation function applied (and isn't grouped by).
Example to display the first photo per user and day (pseudo-SQL): SELECT node.*, DAY(created) AS day FROM node GROUP BY user, day ORDER BY created

Reformulate the problem and filter using joins

The first photo from each user per day can be reformulated as: The photo of each user (per day) that hasn't got an older one on this day.
In SQL this can be realized using joins
SELECT n1.* FROM node n1 LEFT OUTER JOIN node n2 ON n1.uid=n2.uid AND DAY(n1.created)=DAY(n2.created) AND n2.created<n1.created WHERE n2.nid IS NULL

In theory both ways should be expressible in views. But both are rather hard:

views doesn't support ungrouped/unaggregated fields in queries using aggregation. So to work with that you'd need to patch views.
Views provides no way to add additional conditions to relations.

The simplest way to achieve this is perhaps by using views to create the query without aggregation (like in 1.) and then use hook_views_query_alter() to add the grouping:

function yourmodule_views_query_alter(&$view, &$query) {
  $query->groupBy('node.uid')->groupBy('day');
}

NOTE that this won't work as is and without testing. You'd need to take a closer look at the $query generated by views to do this right.


Specify a single node to load a stylesheet on Possible Duplicate:
  Any way to add CSS for a single page/node?

How do I make it so that when a specific node loads (a page with path /some/page) that it also loads a specific stylesheet?

There are several very good solutions, please see the question "Any way to add CSS for a single page/node?"


How to remove webform error message? How to remove webform error message? I need to be able to remove the error message form.

For instance, if I have an email field and for some reason did not pass the validation is not to show a message saying.

  The entered e-mail address "djhshsj" does not appear valid.

So my question is how I can remove that Drupal message?

Update 1: I had to render the error message below the button (I could not just move with CSS ). So I ended up doing my custom validation + error message.  And even though I have my custom validation, webform still validate if that field is correct or not. However, all I want to do is to remove the message NOT the validation.

drupal_get_messages() returns all the messages set using drupal_set_message, which also includes error messages set during form validation. This also clears the messages.

You can then add a custom validate handler to the webform by altering it by implementing hook_form_alter or hook_form_FORM_ID_alter.

In your custom validate handler, call drupal_get_messages() to clear any error messages.


Why Calling the theme path in a multinlingual site adds a language prefix? In my template whenever I call the path to my theme in a particular language it adds a language suffix dir like mysite.com/fr/sites/all/themes/mytheme while I'm expecting a path without a prefix (e.g. mysite.com/sites/all/themes/mytheme).

I'm use drupal_get_path() or path_to_theme().

How can I ensure I get the right path in my template?

You can use base_path() and drupal_get_path('theme', 'yourthemename') functions to get correct path.

Example:

$output = base_path() . drupal_get_path('theme', 'yourthemename');

Result:

/sites/all/themes/yourthemename


How can I build a view that shows other nodes that reference the same node the current node references? Let's say I have homes and neighborhoods (homes reference the neighborhood they're in via a node reference field). On the home detail page I want to show other homes in the same neighborhood.

Seems simple enough, and I've found this: Create a view on a node reference field but it is not quite what I need to do, since I need to find other homes that reference the same neighborhood as the current home does (not ones that reference the current home).

I also found this: Node references view: get other nodes that also reference the same node but I am only using 2 content types (homes and neighborhoods). Any ideas? My brain is tired after trying to think through the relationships and arguments of this thing :)

You should be able to do this with a relationship. Add the neighborhood node reference field as the relationship.  Add NID as your argument and apply the neighborhood relationship that you just created as the relationship to that NID argument. This will tell views to use the NID of the node reference field as the argument.


Drupal 7 Megamenu Construction Using Views in Menu and a menu module? Currently I need to construct a responsive Megamenu and so far I have narrowed down that I need menu_views (https://www.drupal.org/project/menu_views) to output the megamenu items as each dropdown will contain a bunch of recent nodes relating to the sub menu items.

I've been using responsive_menu for my menu, but apparently its not compatible with menu_views as it doesnt output the views in the menu.

It's either I code this responsive menu from scratch, but I rather not if there is a solution for this already that can get me more than 50% of the way there.

Now my question is,  what menu modules would make it compatible with "menu_views"? Or maybe another solution all together. I know about tb_megamenu, but that module seems to have alot of bloat with bootstrap built right into it.

I would try the Superfish module. The Menu Views module page states it should be compatible with the current stable release of Superfish.

Superfish is also responsive out-of-the-box (based on user agent or window width).


Get the node title conditionally in a view rewrite field How can I get the field for the title of the content?

In twig I need to do this (for jssor slider) :

{% if field_titre_url_externe is not empty  %}
  {{ field_titre_url_externe }}
{% else %}
  {{ field_title }}
{% endif %}

but field_title is showing nothing, so what is the name of this?

EDIT :

I'm talking about the title of a node , article or content type

In my frontend, the title has the class views-field-title

See this image for more details (that's what I want to do):

Access the field_url_externe is not working actually... Accessing this field will solve my problem

Is title a field you made or do you mean the node title? Node title can be printed with either {{ label }} or {{ node.getTitle() }}.

Fields that you created on the node, they are rendered out as:

{{ content.field_title }}

Which can be checked as:

{% if node.field_title_external is not empty  %}
  {{ content.field_title_external }}
{% else %}
  {{ node.getTitle() }}
{% endif %}

You can also use {{ label }} instead of {{ node.getTitle() }}.


Drupal 7 single language views I have a website which is developed in three languages. I created a taxonomy vocabulary (product category), which is output from the views. Inside the term gallery thumbnail image products. So, how do single language for the gallery to not have to add three times the same image for multiple languages.

you could set it to language neutral and allow both content in the selected language and language neutral to be shown


Sharing fields and their data between a user profile and a content type? I have a content type called "Profile". This is a standalone content type and may or may not be associated with an actual user on the site.

I thus need to find a way of sharing profile fields between the Drupal user and the new custom content type. In other words, if you edit the "home address" field on the Drupal user's profile page, that field (and its data) should show up on the Profile page associated with the user via EntityReference or Relation or whatever.

Is this at all possible? I know you can reuse fields across content types, but in my understanding, it doesn't share their data (Such that you can use field_something on content type A and again on content type B, but data from A will never show up on B and vice-versa).

Thanks!

(Addendum: My fallback is to just put all of the fields on the new Profile content type, keeping the actual default Drupal user profile relatively sparse. Moreover, I'm curious whether this is at all possible.)

I guess one option would be to use Rules, so that when one entity is saved, the field data is also saved int the field on the other entity.


Edit panel not showing up (Gear -> Edit Panel -> NOTHING??) If I go to a custom panel and click the gear, then click edit panel, the link changes as if a popup appeared, but nothing else shows up. I cleared my cache on my browser, computer, on the website, and even tried it on my coworker's computer but it still doesn't work. I also tried it on Chrome, Firefox, and Safari and still no success.  Any thoughts?

You or one of the modules you installed is loading latest version of jQuery.  In the latest version of jQuery code like

if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {}

does not work.

This code is in one of the Drupal core files. You can find it in modules/overlay/overlay-parent.js file on line 932, 975 and 985.

I do not recommend editing this file, but you can test this change on your localhost to make sure it is the latest version of jQuery which is causing this issue.


Create a form programmatically and display result on template I'm trying to create a simple page with a form.
With the different filled fields I want to execute different EntityFieldQuery in the HOOK_form_submit. To finish I want to display the result of myEntityFieldQueryunder the form like aView`.

For the moment I created a module with HOOK_menu :

function statistiques_menu() {
    $items = array();

    $items['statistiques'] = array(
        'title' => t('Statistics Page'),
        'description' => t('Homepage for statistics'),
        'page callback' => '_homepage_for_statistics',
        //'page arguments' => array('form_example_form'),
        'access arguments' => array('access content'),
    );

    return $items;
}

A simple form here :

function statistiques_form($form, &$form_state) {
    $form['age'] = array(
        '#title' => t('Age'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 3,
        '#size' => 3,
        '#weight' => 0,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#validate' => array('statistiques_form_validate'),
        '#submit' => array('statistiques_form_submit'),
        '#weight' => 10,
        '#value' => t('Click Here!'),
    );

    return $form;
}

I have two functions statistiques_form_validate and statistiques_form_submit under hook_form

Then i send my form and others vars to my template like this :

function statistiques_theme() {
    return array(
        'statistiques_template' => array(
            'template' => 'statistiques',
            'variables' => array(),
        ),
    );
}

function _homepage_for_statistics(){
    global $user;

    $output = '';
    $vartest = 'my var test to template';

    $output .= theme('statistiques_template', array(
        'vartest' => $vartest,
        'form' => drupal_get_form('statistiques_form'),
    ));

    return $output;
}

My template look like this :

<?php print render($form['age']); ?>
<?php print render($form['submit']); ?>

I tried Example module, but this case isn't on this module. There is some cases which are close to my problem, after submit the form data are sent to flash message.

With my code the form doesn't work, I can't submit the form but I think it's a small problem... my real problem will come when I will need to display the result of my form validation to my template under the form or on another template. How can do that ?

Thanks

I recommend adding the results of the query to the form markup-like:

$form['something'] = array(
  '#theme' => 'statistiques_template',
  '#vartest' => $vartest,
);

is equivalent to theme('statistiques_template', array('vartest' => $vartest)) -- the theme system will remove the # from the variable names if #theme is set.

But, of course, you can add the form to the page build as well, see how comment_reply does it:

  $build['comment_node'] = node_view($node);
  $build['comment_form'] = drupal_get_form("comment_node_{$node->type}_form", (object) $edit);

If coding in Drupal 7, forget direct theme calls, strings and the . operator. Work with render arrays instead. It's also a good preparation for Drupal 8 where concatenating strings leads to double escape bugs.


Content Encoding Error - The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression Drupal 7.56, PHP 5, PHP-FPM, multi-site Ubuntu 14.04.1 LTS server

EDIT: it's NOT only when I'm logged in to my site do I get this error:

  Content Encoding Error

  The page you are trying to view cannot be shown because it uses an
  invalid or unsupported form of compression.

It happens 1/3 of the time I try to load a page. If I click "try again" twice or refresh the page twice it will load. I have followed these steps from the accepted answer on Content encoding error after enabling cache, aggregation and compression

$conf = array(
'cache' => '0',
'preprocess_css' => '0',
'preprocess_js' => '0',
'block_cache' => '0',
'page_compression' => '0',
);

I have also checked php.ini, per other resolutions, and error reporting is off.

I checked for PHP error reporting per https://www.drupaleasy.com/quicktips/browser-fail-unsupported-form-compression-related-php-notice and https://www.drupal.org/node/373101 and when I ran the wget command there was no PHP error up top.

The behavior does not change at all after clearing my browser's cache.

FWIW I've tested by disabling every module I could (I'm fighting AddThis right now). I also had to increase the memory limit from 128M to 1000M because I kept getting 500 errors too. See my note on 500 Internal Server Error after logging in

I also had to update a theme.inc file based on this error:

  /e modifier is no longer supported, use preg_replace_callback instead
  in…

as seen at https://stackoverflow.com/questions/38067166/replace-preg-replace-with-preg-replace-callback-still-failing?noredirect=1&lq=1

UPDATE:
the 500 error seems to have been fixed with a permissions reset. I put the memory_limit back to 128M after the permissions reset and no more 500 errors. I got one from Chrome at first but maybe it was a cached thing? Now no more.

Also, per Anson W Han in the comments, I have tried reverting my change to the theme file with no success. And the theme is supposed to be best with PHP 5.2-5.6 and I am running PHP 5.5.9

UPDATE:
the 500 error is NOT resolved after all

Looking in the log file there were some FastCGI references, but in ISPConfig I had PHP-FPM selected. Once it was switched to MOD-PHP all of my problems disappeared.
I can't even.


How to know node/entity ID from a submit handler? How to know node/entity ID from a submit handler of a form created with hook_form()?

I need to make db_update() query on a single row from submit handler called by admin/structure/video/manage/% form created with Forms API.

I would recommend not to use extra submit handlers on node forms. Forms are not the only way that you can create a node. Modules like Feeds, Migrate, etc can create nodes programatically.

If it's a node, and you don't want to alter data that the node itself, implement hook_node_insert and you have access to the whole $node object!
$node->nid would be the node ID if you name your function's first argument as $node.

If you prefer an extra submit handlers, you can access node or entity that is being created/updated in $form (I can't remember the exact key name though).

Install Devel module. Then, you can see what's in the $form array in your submit handler like this:

function mymodule_extra_submit_handler($form, &$form_state) {
  dpm($form); // pretty-prints the entire form.
}

Usually $form['#node'] is the node object, so nid is $form['#node']->nid


Create an image repository I'm trying to create an image repository with Drupal, but I face some problems.
I want to create a node with several images attached, but since the relation between images to nodes can be many-to-many (an image can be attached to more than one node) I don't want to duplicate the same image on the server.
I've tried different solutions but none of them can really fit my needing.

Imagefield solution:

I can easily attach multiple images to a node, but it's hard to reuse the same image.
The best solution would be using filefield_sources, but it's a bit buggy (I can't find a way to use the IMCE integration in a proper way).

Image solution:

It has an image browser, but without search or folder tree, it can't be used with many images.

Did anybody face the same problem and found a good solution?
Thanks in advance.

==UPDATE==

Example:

Product-1 - I can attach Image-A, Image-B, Image-C and Image-D (with image module or imagefield)
Product-2 - I can attach Image-E, Image-F, Image-G and Image-H

Product-3 - I want to attach Image-A and Image-F.
I need to upload them again or I can use Image Browse (part of the Image module) to display an image picker with ALL the images uploaded before (without any search filed or filter).
I see 8 images, I can pick Image-A and Image-F and attach them to the node.

What about Product-1200? At that time I could have 4000 images displayed in Image Browse: it would be really hard to find the one I need to attach to the node!
I would like to find a better way to select the images!

==SOLUTION==

I created two content types: product and image.
Image has an imagefield field.
Product has a nodereference field.
I mass imported all my images with imagefield_import.
I use nodereference_browser with a custom view with all the filters I need to search between Image nodes and select which one to reference.

I haven't tried something like this before, but one way to solve it would be to.

Create a node type to hold the images.
Create a node reference to the image node type.

This would allow you to have several nodes reference the same image node type. You would also be able to tag images and use views on them, if you wanted to display the images stand alone, in a gallery etc.

You would need to do some work, to theme the images the are referenced though the image node, but it shouldn't be a big deal.


What's the most efficient way to get D8 to notice changes to .yml files? I'm taking my first steps with Drupal 8, starting with a custom theme. As a result I'm making incremental changes and testing them.

I've found that in order to be able to tweak CSS you have to turn off aggregation. The normal: change css, drush cc css-js, reload page workflow doesn't work unless aggregation is disabled.

But I'm also having difficulty with Drupal not picking up changes to the yaml files, e.g. add css to the THEME.libraries.yml file - no drush cc ... command has any effect. The only thing I've found to work is drush cr (or drupal cache:rebuild) which adds about 20-30s delay in my workflow.

Is there a quicker workflow for development?

In your development.services.yml file turn twig cache off and debug true. This will assist in theming, twig files are also cached.

Secondly, I think the command you want for yml changes is drush cr. However if they are install yml files, (I believe) they'd only register when a theme is enabled/uninstalled like modules are. So if that's the case you'd need to do that. I've also needed to use cr with libraries.yml changes.

Third, what VM are you using? I can run drush cr and it only takes ~5 seconds on the DrupalVM stack.


Error which i am incountering PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dropjob.semaphore' doesn't exist: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in lock_may_be_available() (line 167 of D:\drop_job\includes\lock.inc).

Can anybody help me to solve it
I will be greatful

If the table doesn't exist (for some reason), you can create it manually by executing an sql query.

Here is the query to create the semaphore table:

CREATE TABLE `semaphore` (
  `name` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique name.',
  `value` varchar(255) NOT NULL DEFAULT '' COMMENT 'A value for the semaphore.',
  `expire` double NOT NULL COMMENT 'A Unix timestamp with microseconds indicating when the semaphore should expire.',
  PRIMARY KEY (`name`),
  KEY `value` (`value`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Table for holding semaphores, locks, flags, etc. that...';


How to access personal contact form in search Using Drupal 7. All of the people on my site have personal contact forms. When I type their name into the search bar, I get 'no results'.

I need people to be able to find users' personal contact form links by using the search function.

I'm using the core Search module and have enabled 'users' to be included in the search, but no results come up, regardless of which name I use. Site has been re-indexed, caches flushed, etc.

All users have a status of 'authenticated' and permissions have been set on 'contact' and 'search' to allow the results to show.

Any help is appreciated. Thanks.

Okay. I was under a deadline so I came up with an annoying but functioning solution.

1) I added the Search by page module (https://www.drupal.org/project/search_by_page) and enabled it.
2) I made a new search environment by going to admin/config/search/search_by_page.
3) In the new search environment, I enabled all the content types I wanted the module to pull.
4) How I got it to pull users' contact pages was:
5) Go to the enironment I made and clicked 'edit'
6) On the top right of the page are two tabs: 'General settings' and 'paths'
7) I clicked on 'paths'and then clicked 'add new path'
8) I opened a new browser window and navigated to the 'People' tab. I clicked on a user and selected their 'Contact' tab, and copied the path (in my case, user/number/contact
9) I went back to the 'add new path' tab and pasted that info in the 'page to index' section
10) I entered a page title (Contact Mr. Smith) and saved. Clicked on 'add new path' for next user.
11) Repeated steps 7-11 for all 50 users.
12) Re-indexed site by running cron. Voila, contact pages come up in search results.

This was a cumbersome, time-consuming way of doing this, and I'm sure there's a better solution. However, if you're pressed for time like I was, I hope this helps someone.


how to provide a content type variable to region--header.tpl.php I want to hide some inline html from header for specific content type. How cud I provide a content type variable to region--header.tpl.php to put a php condition to hide the html?

Try this...
https://www.drupal.org/node/115419

<?php
  // Only show if $match is true
  $match = false;
  // Which node types
  $types = array('book', 'news', 'anothernodetype' );
  // Match current node type with array of types
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load(array('nid' => $nid));
    $type = $node->type;
    $match |= in_array($type, $types);
  }
  return $match;
?>


What is the difference between the Load and Render objects in Devel? When viewing a Node in the Devel tab, what are these different objects Load and Render? How and where would I have access to them in the theme layer?

The "Load" tab shows the output of node_load(), while the "Render" tab shows the output of node_view(). In the first case, the output is a node object; in the second case, the output is an array as accepted by drupal_render().


Including template footer.tpl.php within another template page.tpl.php I am looking for simple way to include footer.tpl.php that is just html block into another template like page.tpl.php. In Grails/Groovy that is as simple as

<g:render template="side_menu"/>

Is there a same simple way(preferred no use any panels, custom modules, etc) in Drupal? Thank You

The way to include another .tpl.php file is the include function.

Another idea is to add your footer as a region in the page.tpl.php and assign a region wise theme as defined in Drupal 7 Template (Theme Hook) Suggestions

  region--[region].tpl.php
  The region template is used when a page region has content, either from the Block
  system or a function like hook_page_build(). Possible region names are determined by the  > theme's .info file.


Can the BaseFieldOverride class be used to implement hook_entity_bundle_info()? I need to implement hook_entity_bundle_info(), and I noticed that the documentation includes a link to Finalize API for creating, overriding, and altering code-defined bundle fields. In short, that issue says that is wrong to use the BaseFieldDefinition class because that class marks the field as a base field, which is not true, since the field is being added to a bundle.

Can the BaseFieldOverride class be used to implement hook_entity_bundle_info()?

Doing so, the example given for hook_entity_bundle_info() would become the following one.

function hook_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  // Add a property only to nodes of the 'article' bundle.
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    $fields = [];
    $base_field_definition = BaseFieldDefinition::create('string')
      ->setLabel(t('More text'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedMoreText');
    $fields['mymodule_text_more'] = BaseFieldOverride::createFromBaseFieldDefinition($base_field_definition, $bundle);
    return $fields;
  }
}

According to the issue you linked the answer is no:

  So, in theory, contrib modules can implement non-config-based bundle fields, but we don't provide an implementation class with which to do so.


How to display tags of content filtered by a different tag I have a content type that has 3 taxonomy fields (Year, Project & Type, respectively).

On the top page of the view I want to display all terms of the Year-vocabulary, this is no problem. I rewrite the field so it links to

/work/Year

On the next page I want to show all the unique Project-terms for the selected year.

Example:

Project A: Year: 2014, Project: Scanning Paper, Type: Painting
Project B: Year: 2014, Project: Scanning Paper, Type: Drawing
Project C: Year: 2013, Project: Leaving , Type: Painting
Project D: Year: 2014, Project: Afterlife, Type: Painting

If the year 2014 is selected, I want the next view to display all unique projects:

Scanning Paper
Afterlife

I've been trying this to accomplish this using Views, and been working at a solution for a couple of days now, but I can't figure it out. I've tried a lot of things, searched here and elsewhere, but haven't find a solution. I'm beginning to think maybe the approach with taxonomy terms isn't right, but I need some guidance.

Thank you.

You will need to use three views.

The first view can be either a view of taxonomy terms (easy enough), or a view of your content type with a relationship, taxonomy terms on node. Use this path: work

If you select the second option you will get duplicate rows, and you will have to use aggregation. You will need three fields: tid (hidden), type (hidden and aggregation set to count), and term name (rewrite it to a link with this: work/[tid]).

The second view will have a path: work/% and will be a view of your content type. Add two relationships, one to taxonomy terms on node and select year, and another to taxonomy terms on node, and select project. Give them each a descriptive identifier. Now add a contextual filter: The tid of a taxonomy term, and select the relationship of the year taxonomy vocabulary. Now you will get a lot of duplicates. Again set aggregation on and this time you might have to add fields content type (hidden and aggregation count) as well as tid (hidden, relationship to year vocab, aggregation count). Add two hidden tid fields (for the link construction), one with year relationship, other with project.
Add your link field and rewrite as link like this: work/[tid]/[tid_1]

The third view is more of the same. It will have path of word/%/%. You will add one more relationship and contextual filter than you did for view 2.

In view 1 if you do it based on your content type then only years that are being used by your content will show. If you do it as a taxonomy view then all year terms will show, and depending on your content some of these term links will then navigate to empty views.

And when you build your views start off without any sorting on them as this will give initial issues with aggregation. You can add sorting back after you have a working solution.


Separate page.tpl file for URL I have created a custom module with page URL like $items['testpage/get']. How can I create a separate page.tpl file for this URL? Link is like: http://199.x.x.x/mysitename/testpage/get.

It's based upon the path.  In D6:

page-testpage-get.tpl.php

In D7:

page--testpage-get.tpl.php

(Although D7 might want page--testpage--get.tpl.php due to its love of double dashes :)

All about templates and their suggestions can be found here:

D6: http://drupal.org/node/1089642

D7:  http://drupal.org/node/1089656


Change text displayed when cart is empty I'm using Drupal 7 with Commerce and I'd like to change the text shown when the user visits /cart and they have not added any items, from the default "Your shopping cart is empty." to a custom message, preferably that contains HTML.

I have tried adding custom text under no results behavior commerce_cart_form view with no luck.

What is the best way to do this?

I think a theme function called commerce_cart_empty_page is used. So you should be able to add a function:
MYTHEME_commerce_cart_empty_page()
to your themes template.php file and return whatever html you want.

You can also do the same for the cart block with a theme function MYTHEME_commerce_cart_empty_block()


Views caching dont show changes I'm having a problem with views and caching. Within a custom module, i do changes on my database, which is working fine, but my view won't show that changes until I clear all caches.

I tried to deactivate views-caching here "admin/structure/views/settings/advanced"
Caching in the view is deactivated too
And the whole caching is deactivated here "admin/config/development/performance"

But I still have to clear all caches on every change I make to see what I did. Is there a chance to stop caching for that view by code in the module? Or any other possibility?

EDIT: I now tried a module called "CacheExclude" and

$GLOBALS['conf']['cache'] = 0;
drupal_page_is_cacheable(FALSE);
$conf['cache'] = FALSE;

but no change :(

EDIT 2:
Here is the code where I change the field in the database:

foreach($books as $book) {
    $query = db_update('field_data_field_zuordnung')
        ->fields(array(
            'field_zuordnung_value' => 'verkauft',
            ))
        ->condition('entity_id', $book->product_id, '=')
        ->execute();
}

The change is done in the DB, but it isn't shown in the view. After that, I use drupal_goto to move to a "you're done site".

You should ideally be using the Field Attach API to avoid these problems.

Or for a quick solution have a look at field_attach_update where at the end of the function, it clears the field cache:

$entity_info = entity_get_info($entity_type);
if ($entity_info['field cache']) {
  cache_clear_all("field:$entity_type:$id", 'cache_field');
}


How to upgrade Acquia desktop to php 7.1? Drupal 8.4 requires php version greater than 7.1 . In acquia devdesktop default we are getting php 7.0.  How to upgrade php 7.0 to php 7.1 in Acquia dev desktop?

Thank you.

DevDesktop 2 now supports PHP 7.1.

Updated components in the latest version:

  Added option to use PHP 7.1
  MySQL Windows build) updated to 5.6
  Percona (Mac build) updated to 5.6
  Drush updated to 8.1.15
  In addition, the feedback submission function within the app has been fixed.


Why does the "Registration List" tab not appear for my events for users with adequate privileges? I'm using the RNG events module in D8 - when a user with adequate privileges clicks the event tab, they can see and edit all fields, but the "Registration List" tab doesn't show, and they can't see the list of current registrants without the use of a custom view.

This may or may not be connected to the problem I'm having here - How do I limit permissions to manage an event?

Figured it out - I had installed and was using the Field Permissions module which takes over any and all other permissions set in any of those other places. Once I edited each field on the event content type with custom permissions everything works great.

This still doesn't solve or explain the missing Registration list tab for admin users per How do I limit permissions to manage an event? though.


Allow users to email a file and create a new post Tumblr allows users to upload files using a randomly generated email account that is assigned specifically to each user. I have a content type called "Video" and I would like to find a way to randomly generate an email address using my site's domain and allow the user to attach a video file and meta data. When they send it, it gets uploaded to the site just like it would if they submitted the form online. I am also using Amazon SES if that could be helpful to solving this.

You have two options. The less efficient (but easier) way is to keep it in Drupal

The more efficient (and more difficult) way is to do a bit of this outside Drupal and hack at your MTA and/or use something like Amavis to do it.

Since you're on a Drupal site, I'll give you a quick rundown of how I might do this if I had to keep it in Drupal.

What you need to do is have the random generated email checked by Drupal regularly.

Create a module that periodically (via cron) logs in to each user's associated email address (these should be IMAP accounts!).  If it finds a message that has the right subject line to trigger a new content post, then download the attachment and save it to the file system.

Keep in mind, this could be a crazy thing to do if you're dealing with a lot of users.  The better option would be to have the emails processed outside of Drupal, and then use something else to trigger the Drupal content creation.

No matter which way you go, you're looking at quite a bit of programming. I have never seen a module that does this.


Print profile2 fields in user-profile.tpl.php Been trying to print the profile2 fields in the user-profile.tpl.
The fields are of type: taxonomy reference field and link field.

The documentation provided in drupal doesn't work.

Workarounds provided in the profile2 issue queue here and here either prints the current users value in every profile or renders it twice.

It'll really great if someone can help me with this. Thanks for your time.

In user-profile.tpl the below renders the fields twice, once within the div and other without it from "print render($user_profile);"

    <div class="athlete-info">
    <?php $user_uid = $elements['#account']->uid;
    $profile = profile2_load_by_user($user_uid, 'athlete');

     print drupal_render(field_view_field('profile2', $profile, 'field_name', 'value'));
     print drupal_render(field_view_field('profile2', $profile, 'field_twitter','value'));
     print drupal_render(field_view_field('profile2', $profile, 'field_facebook', 'value'));
     print drupal_render(field_view_field('profile2', $profile, 'field_role', 'value'));
     ?>
     </div>

But this causes an error page on other user roles who don't have to fill up the athlete profile type. :(

EDIT: I am using the profile 2 module to create a profile called athlete with few extra fields like field_facebook,field_twitter and assign them to users of a particular role.

If these fields are already a part of $user_profile and what you are wanting to do is print them in another place/div on the page, you can do something like this:

<?php
  hide($user_profile['field_name']);
  hide($user_profile['field_twitter']);
  hide($user_profile['field_facebook']);
  hide($user_profile['field_role']);
?>
<div class="profile"<?php print $attributes; ?>
  <?php print render($user_profile); ?>

  <?php print render($user_profile['field_name']); ?>
  <?php print render($user_profile['field_twitter']); ?>
  <?php print render($user_profile['field_facebook']); ?>
  <?php print render($user_profile['field_role']); ?>

Eg, hide() the fields you want to print elsewhere, then render() the rest of the profile and then finally render() those specific fields where you want them.

Now, if you are getting an error because these don't exist everywhere, you can do something like this:

<?php if (isset($user_profile['field_facebook']): ?>
  <?php hide($user_profile['field_facebook']); ?>
<?php endif; ?>

and a similar wrapping around the final printing (ADDITION: this appears to be unneeded as I didn't get any errors when I did a hide($user_profile['i_got_nothing_to_hide']); and a quick look at the code for hide and render shows that they pretty smart/sneaky about being passed undefined variables or keys)

Or you could check on the user role,  but if this is going to begin to put a lot of php logic into the template, you may want to investigate preprocessing() it and using a special template for the user profile of the users with this/these roles.


Cant get desired results for multiple sort criteria in a view I have created a points table for a race event and would like to sort the results in a specific order.

I am working with a table view that contains 3 sort criteria:

the race event (working fine done via table settings)
class of a car A, B , C and
the points each driver receives.

I would like the order to be A then points B then points C then points regardless of what class has the highest points.

Problem:

If for example a C class car has points higher than any B class car then the stacking order is ACB. As soon as any B class car gets higher points than the C class car then the order is ABC (how I would like it). This can be seen in class A where Driver 2 has the lowest points of all.

I have tried re arranging the sort order but that does nothing.

Can i suggest removing the grouping and getting the single table to display as you would like it and then once you have done that apply the grouping. It sounds as if youre sorting by points not by car class - can you change the sort to car class then add the group.

Or group by event and then sort by car class and points.


Best way to approach users voting on and identifying content? I am working on a Drupal 7 website, Double Enders, where users can view and add individual boats, categorizing them by design.

I already have several boats that have not been identified by their design. I am planning on using views to allow users to view the boats that do not have designs associated with them. I would like to also give users a drop-down menu with all the designs (which is a view that I use elsewhere in the site) and allow them to use this drop-down menu to identify/vote on what type of design the boat is, tallying their votes.

Looking through the voting modules, it does not appear that any of them allow one to use a view as the options a user can select between. Instead, they all seem to provide some variation on ratings or yes/no.

I am considering using the Voting API module to build the functionality myself. However, before I go down that road, I was wondering if I had missed a module that I could use or another way to get the functionality I desire. Does anyone have any suggestions, or am I right to proceed using the Voting API module?

Have a look at Flag module. It supports adding fields to a flag, so a user could first flag a boat ("I can identify that design!") and then select one of the known designs on the flagging form.

Whatever you end up using, I'd like to read what you choose, and why!


Disabling the site cache brakes the page output I have just finished my development and uploaded a website to a hosting. But unfortunately I've got another weird problem..

If I disable the site cache another template is used for rendering a view node.
I cannot catch the error. The problem is that in case I disable all caches, this problem appears. But when I try to debug the problem it disappears))
So I am not able to find what is wrong with it ?
Sometimes it appears after commenting these lines

#$settings['cache']['bins']['render'] = 'cache.backend.null';
#$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Sometimes it appears after disabling Twig Debug

The problem that it swaps view node templates between two views. For exampl I have a view for rendering teasers, and another view is for rendering a node preview. So it swaps them. I really cannot understand what is going on and what is the problem.

Please suggest what can cause such weird behavior ?

Thanks

NOTE 1

The same problem occurs locally when I disable caches.

NOTE 2

I've found the weird part of debug output

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_unformatted__latest_works' -->
<!-- FILE NAME SUGGESTIONS:
   x views-view-unformatted--latest-works.html.twig
   x views-view-unformatted--latest-works.html.twig
   * views-view-unformatted.html.twig
-->

The same template is suggested twice

NOTE 3

I've noticed another weird behavior

#$settings['cache']['bins']['render'] = 'cache.backend.null';
#$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Comment these lines the view on the main page doesn't work, outputs nodes with template from another page.
Go to menu, Devel -> Clear Cache.
Now view on the main page works correctly, but on the other page output nodes using template from the main page.

And these behavior repeats

FINALLY

The problem is caused by the render cache I guess. To get this error I have to do following steps :

Consider there are two pages the front and the category page.
If current page is displayed incorrectly, then stay on this page open admin panel, clear the site cache, refresh the page - everything is rendered correctly.
Go to the category page, now it rendered incorrectly and nodes that are also present on the front page rendered incorrectly using the front page template.
If I clear cache again and refresh the category page it will work, but the front page will be rendered using the view template from the category page.

I hope I've described the problem clearly.
It seems that the problem is similar to that one https://www.drupal.org/node/2359955

It seems that I've found a temporary solution to this problem.

Edit core/includes/entity.inc

Comment reset check lines.

function entity_view(EntityInterface $entity, $view_mode, $langcode = NULL, $reset = FALSE) {
  $render_controller = \Drupal::entityManager()->getViewBuilder($entity->getEntityTypeId());
  //if ($reset) {
    $render_controller->resetCache([$entity]);
  //}
  return $render_controller->view($entity, $view_mode, $langcode);
}

If someone has the same problem, please let me know whether the solution works.


How to programmatically add links to the links variable I am using Drupal 6 and would like to modify the $links variable to include other links programmatically. I have searched high and low on Google on how to do this to no avail. Does someone know how to do this?

Drupal 6

In Drupal 6, you can't use hooks or alter hooks inside themes, so you'll need to create a custom module to modify the links. Once done, you'll want to implement hook_link() (if you're creating a new link) or hook_link_alter() (if you want to modify an existing link).

Adding a new link:

example_link($type, $object, $teaser = FALSE) {
  $links = array();
  // Add a custom link to nodes
  if ($type == 'node') {
    $links['example_mylink'] = array(
      'title' => t('Test link'),
      'href' => 'foo',
      'attributes' => array(
        'title' => 'Test link',
      ),
    );
  }
  return $links;
}

Modifying existing links:

example_link_alter(&$links, $node, $comment = NULL) {
  // Remove the read more link
  unset($links['node']['node_read_more']);

  // Change the title of the read more link
  $links['node']['node_read_more']['title'] = t('More information');

  // Move read more link to first slot
  $link_read_more = $links['node']['node_read_more'];
  unset($links['node']['node_read_more']);
  $links = $links['node'];
  $links['node'] = array(
    'node_read_more' => $link_read_more,
  ) + $links;

  // Move link to the last slot
  $link_read_more = $links['node']['node_read_more'];
  unset($links['node']['node_read_more']);
  $links['node']['node_read_more'] = $link_read_more;
}

Drupal 7

In Drupal 7, this is a little more straightforward, as themes can implement alter hooks. The alter hook you're looking for is hook_node_view_alter():

function example_node_view_alter(&$build) {
  // Remove the read more link
  unset($build['links']['node']['#links']['node-readmore']);

  // Add your own custom link
  $build['links']['node']['#links']['example-mylink'] = array(
    'title' => t('Test link'),
    'href' => 'foo',
    'html' => TRUE,
    'attributes' => array(
      'title' => 'Test link',
    ),
  );

  // Move read more link to first slot
  $link_read_more = $build['links']['node']['#links']['node_read_more'];
  unset($build['links']['node']['#links']['node_read_more']);
  $links = $build['links']['node']['#links'];
  $build['links']['node']['#links'] = array(
    'node_read_more' => $link_read_more,
  ) + $links;

  // Move link to the last slot
  $link_read_more = $build['links']['node']['#links']['node_read_more'];
  unset($build['links']['node']['#links']['node_read_more']);
  $build['links']['node']['#links']['node_read_more'] = $link_read_more;
}

You can place this directly in your template.php file.


How to rewrite View SQL query to bypass MySQL query cache (SELECT SQL_NO_CACHE) I would like my View not to use MySQL cache as one of the checks in WHERE clause keeps changing with current time (granularity set to second). Caching this query doesn't make much sense. I would like to convey this to MySQL server by rewriting SQL to SELECT SQL_NO_CACHE. I looked at hook_views_query_alter(&$view, &$query) with a hope to achieve it but I couldn't figure out how $query need to be altered for this. Usecases found so far talks only about changing order by and where clause conditions. Any directions pertaining to this will be greatly appreciated. Thanks in advance.

I don't want to say that this is impossible, but it's very close to be true.

The problem is that Views uses the Drupal SQL builder, so when making a select query, it utilizes the SelectQuery which again uses PDO from PHP. PDO can be used in two ways, either you feed it a query, or you can use it to build a query by instantiating the class and dosing stuff like

$query = ...;
$query->addField(...);
$query->addCondition(...);
$result = $query->execute();

The challenge is that you need to tell PDO that you don't want to make a regular SELECT query but instead an SELECT SQL_NO_CACHE query. I don't know if that is possible of how you would do it if it were. Even if it is possible, you still need to figure out how to do it through all the abstractions of classes created by PDO and Drupal and Views.

Drupal has a hook you can use to alter queries in general which probably will be the easiest route if you can figure out the above: hook_query_alter, alternatively you can subclass views_plugin_query_default defined in Views, where you can add alter how the query is created to add SQL_NO_CACHE. Again PDO and abstractions is the challenge.

If you are using Drupal 6 this should be more simple and you can probably use something like hook_db_rewrite_sql.


How to add asc and desc sort symbols in drupal views? I have a drupal 7 view, consists of table. I need to add sort symbol (both asc and desc)
in view header by default if no sorting applied.

I tried with altering views-view-table.tpl.php file, and added asc, desc images for each header.

But I need proper solution, Is there any hook there to alter the table headers?

I need table headers like here : http://ng-table.com/#/sorting/demo-sorting-basic

Implement theme_tablesort_indicator(). Please replace your theme name with example

function example_tablesort_indicator($variables) {
  $style = $variables['style'];
  $theme_path = drupal_get_path('theme', 'example');
  if ($style == 'asc') {
    return theme('image', array('path' => $theme_path . '/images/arrow-asc.png', 'alt' => t('sort ascending'), 'width' => 13, 'height' => 13, 'title' => t('sort ascending')));
  }
  else {
    return theme('image', array('path' => $theme_path . '/images/arrow-desc.png', 'alt' => t('sort descending'), 'width' => 13, 'height' => 13, 'title' => t('sort descending')));
  }
}


Adding a token to a views block title I am displaying some view blocks on a page. The content is being filtered by passing the nid from the url into some custom php. I wish to change the block title to use a field from the node in question. Is this possible?

For Views 3 , the given answers are partially incorrect. Tokens are allowed in the header area of view blocks. The only tokens available are for the fields used in the view. So you can set the field that will be used only for its token to hide.

You have to select the Global: Text area option in Header, check Use replacement tokens from the first row and select the token from the Replacement Patterns dropdown.


Show a view's filter as a menu I'm recently working on a view and i want to show the filters (two of them) as a menu. This means:
    That both filters can't be used at the same time (most important, a.k.a if one filter is already used and we click on the second, the first one is initiated),
    That the list of elements of each filter is shown when the mouse is on (less important)
    That the -All- should be replaced by the name of the filter (least important)

I have tried to look for it in the internet and find some answers that didn't work for me (here is the solution for an oldest version of drupal https://www.drupal.org/node/1111712)

Thank you ^^
Edit : I've developed a function to choose between both filters, but it's still not working

$testpriorite=0;
if((isset($form_state['input']['term_node_tid_depth_1']))&&(isset($form_state['input']['term_node_tid_depth']))){
    if(($form_state['input']['term_node_tid_depth_1']!="All")
      &&($form_state['input']['term_node_tid_depth']!="All")){
        if($testpriorite==1){
            $form_state['input']['term_node_tid_depth_1']="All";
        }elseif($testpriorite==2){
            $form_state['input']['term_node_tid_depth']="All";
        }
        $testpriorite=0;
    }elseif ($form_state['input']['term_node_tid_depth_1']!="All"){
        $testpriorite=1;
    }elseif ($form_state['input']['term_node_tid_depth']!="All"){
        $testpriorite=2;
    }

here term_node_tid_depth and term_node_tid_depth_1 are my two filters. Does someone have an idea ?

thanks again

Instead of calling directly the view you call a rules link.

The rules link is calling the view with the desisered parameters for the view. In this case the filter can be used as a contextuel filter.

No programming needed.


Complex View Involving Separate Entities / Taxonomy Vocabulary / Content - Distinct Given the following Content Type: Smartphone

Taxonomy Vocabulary: OS: Android / iOS / Windows / Blackberry

Taxonomy Vocabulary: Color: Red / Blue / White / Black / Yellow

OS and Color is a Taxonomy Vocabulary which is term referenced in the content type smartphone.

Now the question is:

How do you setup a view to display only the COLORS that are available for the Android OS? I do not care about what phone it is. Example of this contextual path would be: example.com/android-colors

That in effect would just give me a list of all available colors that androids are in. Since OS and color has no direct relation, you would have to create a view of smartphones then GROUP THEM BY color while the contextual filter grabs the %android% arguement via the path.

The problem with this is that there will be thousands of records since each result is unique since your querying the smartphone table. Distinct setting in the query dialog box does not apply since each result is technically not distinct.

You can cheat a little and use Views Limit Grouping to help do this.

I created a view of smart phones with the path being smart-phones/%/colors. The only argument I need is for the OS. Add a contextual filter for the mobile OS using "Content: Has taxonomy term ID", filter by the term name. Under your fields to be shown, just select the color.

Using the Group Field (with Limit) formatter, we'll group by the color and show 0 items. Now if there are smart phones that have a color selected, it should show up in this list. In my screenshot you can see that I am only showing Blue and Orange, but in my taxonomy I actually have Blue, Green, Orange, and Red available - but I have no phones that are Red or Green.

From here, all you need to do is rewrite the color url to go to whatever other view you would like, such as smart-phones/%OS/%Color