Unit Testing Mock Guzzle Response I'm trying to test a method that makes an HTTP request via Guzzle, so I can see if my code that filters that response is working. I have a mock json response in a json file that I want to use to test it. This is simply a saved version of an actual response.

I know you can mock methods e.g. this would override the get method to return a mock Guzzle Response. How do you mock a Guzzle response in Drupal 8?

    $this->mockHttp->expects($this->any())
      ->method('get')
      ->willReturn($mockGuzzleResponseShouldGoHere);

The mock Guzzle response needs to have a mock method getBody so I can do something like this:

$this->mockHttp->expects($this->any())
      ->method('getBody')
      ->willReturn(__DIR__ . 'Mocks/membership-classes.json');

and make sure that getBody returns my mock json file.

Method to test that makes a Http Guzzle request

<?php

/**
   * Call the GetMembershipClasses service.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   */
  public function getMembershipClasses() {

    try {
      // Load configuration for this module.
      $response = $this->http_client->get(
        $this->getBaseUrl() . '/2014/06/membershipClasses', [
          'headers' => $this->getAnonymousHeaders(),
        ]);

        $response = json_decode($response->getBody());

        // Get to the meat of the response.
        $response = $response->GetMembershipClassesResponseMessage->MembershipClasses->MembershipClass;

        // Validate returned data.
        $filtered = array();
        foreach ($response as $membership_class) {
          $membership_class->MembershipClassCode = $this->removeSpaces($membership_class->MembershipClassCode);
          if ($membership_class->IsActive === TRUE) {
            $filtered[] = $membership_class;
          }
        }
        return new JsonResponse($filtered);
    }
    catch (RequestException $e) {
      return $this->handleError($e);
    }

  }

And the test class

<?php

/**
 * Class RouteControllerAnonymousTest.
 *
 */
class AnonymousWebServicesTest extends UnitTestCase {

  /**
   * Mock of http_client service.
   *
   * @var \GuzzleHttp\Client
   */
  protected $mockHttp;

  /**
   * Mock of state service.
   *
   * @var \Drupal\Core\State\State
   */
  protected $mockState;

  /**
   * Mock of config.factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $mockConfigFactory;

  /**
   * Set up method which is called before any tests are
   * run. Mocks of the services that the class being tested rely on are
   * created.
   *
   * @return void
   */
  protected function setUp() {

    parent::setUp();
    $mockHttp = $this
      ->getMockBuilder('GuzzleHttp\Client')
      ->disableOriginalConstructor()
      ->setMethods(['get', 'getBody'])
      ->getMock();
    $this->mockHttp = $mockHttp;

    $mockState = $this
      ->getMockBuilder('Drupal\Core\State\State')
      ->disableOriginalConstructor()
      ->getMock();
    $this->mockState = $mockState;

    $mockConfigFactory = $this
      ->getMockBuilder('\Drupal\Core\Config\ConfigFactory')
      ->disableOriginalConstructor()
      ->getMock();
    $this->mockConfigFactory = $mockConfigFactory;

  }

  /**
   * Test the getMembershipClasses method.
   */
  public function testGetMembershipClasses() {

    // This needs to mock a Guzzle response from a get request
    $this->mockHttp->expects($this->any())
      ->method('get')
      ->willReturn('The mock guzzle response should go here);

    $this->mockHttp->expects($this->any())
      ->method('getBody')
      ->willReturn(__DIR__ . 'Mocks/membership-classes.json');

    $anonymousWebServices = new AnonymousWebServices(
      $this->mockHttp,
      $this->mockState,
      $this->mockConfigFactory
    );

    $membership_classes = $anonymousWebServices->getMembershipClasses();
    var_dump($membership_classes);
    // Insert some assert statement here

  }

}

Guzzle includes a mock handler that lets you provide a mock HTTP response. Docs are at http://docs.guzzlephp.org/en/latest/testing.html. Here's how you might use it in your unit test:

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

/**
 * Test the getMembershipClasses method.
 */
public function testGetMembershipClasses() {

  $body = file_get_contents(__DIR__ . '/Mocks/membership-class.json');
  // This sets up the mock client to respond to the first request it gets
  // with an HTTP 200 containing your mock json body.
  $mock = new MockHandler([
    new Response(200, [], $body),
  ]);
  $handler = HandlerStack::create($mock);
  $this->mockHttp = new HttpClient(['handler' => $handler]);

  $anonymousWebServices = new AnonymousWebServices(
    $this->mockHttp,
    $this->mockState,
    $this->mockConfigFactory
  );

  $membership_classes = $anonymousWebServices->getMembershipClasses();
  $membership_classes = json_decode($membership_classes->getContent());

  $this->assertNotEmpty($membership_classes);
  foreach ($membership_classes as $membership_class) {
    $this->assertTrue($membership_class->IsActive === TRUE);

  }

}

You can queue multiple mock responses by adding them to your handler at creation time:

  $mock = new MockHandler([
    new Response(200, [], $body),
    new Response(400, [], 'Request malformed.'),
  ]);

Or you can add them after your client has already been instantiated, as long as you keep a reference to your mock handler around. If you have multiple test methods, this is a lot easier to read and maintain:

public function setUp() {
  $this->mockHandler = new MockHandler();
  $handler = HandlerStack::create($this->mockHandler);
  $this->mockHttp = new HttpClient(['handler' => $handler]);
}

public function testSomething() {
  $this->mockHandler->append(new Response(200, [], 'apples and bananas'));
  $responseBody = $this->mockHttp->get('http://example.com')->getBody();
  $this->assertEquals($responseBody, 'apples and bananas');
}


Hide zip in addressfield form on commerce checkout pane? How can I hide some fields from addressfield module (for example zip code) on checkout process if certain country is selected?
E.G. If US country selected then hide postal code field. If CA country selected then show postal code.

Clive is correct. The module already adjusts the form as appropriate. If you aren't seeing this, you must have something interfering with the Ajax based update of the form element.


Show teasers from both content type and Users together in a view I would like to be able to create a page to show teasers from content created with a certain content type, say "Company" together with teasers from Users content.

Until now, I just managed to create either a view to show the teasers of the Company content type, OR the teasers of the Users. But not both.
When I add a relation, I can use fields of both in the same block, but I would like to show a page with separate blocks of both companies and users together.

How should I do such a thing, if even possible?

Since you say that you would like to show a page with separate blocks of companies and users, there's no need to do this all in the same View.

Create two different Views with Block displays. One for the teasers of Company content type, one for the teasers of the Users. (You have done this much already.)

Then, place both of those Blocks in theme regions on the same page, and they should both appear ... together, but separately.


How can I display a Google map with Search API Views and Search API DB I am using Search API with Search API DB, and Facets, with Search Views.  I want to display a map to plot the results from the search.  Is this possible?  I have looked everywhere and can't seem to figure it out.

My nodes currently use geofield for the individual node pages.

Have you ever tried these two modules?
https://www.drupal.org/project/gmap
https://www.drupal.org/project/location

With these two modules, you can create google maps and put your location data into a referenced google map.


Metatag images don't work anymore after updating I was on Drupal 8.5.x and Twitter cards and Open Graph on Facebook were displaying correctly.

After updating to Drupal 8.6.1, the images don't display anymore. The others data (title, description, url...) are OK, it's juste an images problem.

So I've checked the tokens used by the Metatag module and they are the same I used in Drupal 8.5.x without any problem.

The token I use for images is : [node:field_image_article:entity:field_image]
Indeed, in my content type, I use a field named "Image article" that contain several fields (title, author, licence...) including an "Image" field where I upload the image.

When I look at the source code of my webpages, I have this :

<meta name="twitter:image" content="https://example.com" />
<meta property="og:image" content="https://example.com" />

instead of the complete URLs of the images...

Does anyone know how to solve this ? Thx.

This issue is documented here : https://www.drupal.org/project/metatag/issues/2994433

For the moment (21/09/18), there are two solutions :

add :entity:url at the end of the token
downgrade to Metatag 1.5 instead 1.6

Using first solution, change [node:field_image_article:entity:field_image] for [node:field_image_article:entity:field_image:entity:url] did the job for me.


Make search block appear for anonymous user I have defined a region in my theme in which I've placed the search box. But, it only appears when a user is logged in. I checked to see the visibility and made sure the block is also visible to anonymous users; but it doesn't show up.
I searched online for the issue but I wasn't able to find a good (working) solution. Is there a way to do so?

My search block visibility settings:

There is one more permission need to set at admin/people/permissions. Under Search give  'Use search ' permission for anonymous user


Views escapes HTML tags in node body I'm creating a view that displays a few fields from a specific content type. Among the fields is the trimmed nody body. The problem is that the HTML tags in the body are escaped and are visible as source in the view.

So instead of

  Lorem ipsum dolor sit amet, in dolores propriae sapientem vim. Per no
  autem minimum iudicabit, ad numquam eloquentiam ius. Quas iusto ea
  vis. Mea quaestio gloriatur mediocritatem et. Mei rebum postea ne, his
  malorum necessitatibus ei. Ea pro animal mandamus, ad pri postea
  eripuit.

I get the following:

Lorem ipsum dolor sit amet, in dolores propriae sapientem
  vim. Per no autem minimum iudicabit, ad numquam eloquentiam ius. Quas
  iusto ea vis. Mea quaestio gloriatur mediocritatem et. Mei rebum
  postea ne, his malorum necessitatibus ei. Ea pro animal mandamus, ad
  pri postea eripuit.

From what I understand Drupal 8 escapes everything by default, so I suspect this has something to do with my problem. I looked at every setting I could find in Views, but I couldn't find anything that would change the escaping of HTML tags.

How can I output the body of a node unescaped in a Drupal 8 view?

I'd recommend against accepting this right away even if it works for you because I suspect it isn't the best answer, but I ran into this same problem and I ended up just overriding the template with raw HTML like so:

Copy core/modules/views/templates/views-view-fields.html.twig to the appropriate location in your own theme (e.g. themes/custom/mytheme/templates/views/views-view-fields.html.twig for me)
For each variable output in the loop add the raw filter, e.g. {{ field.content | raw }}
Clear your caches and refresh the page to see the result

I think this should be okay since any HTML that comes from the views fields should already be filtered of anything harmful (and I believe this is more or less how it used to be done - take a look at the old PHP views templates) but if someone knows better please do correct me in the comments.

EDIT: I noticed one of the related questions (Drupal 8: HTML isn't rendering, HTML tags are being printed) has a link to this issue: https://www.drupal.org/node/2363423 which I believe is related, so this workaround may soon no longer be necessary.


How do handle exceptions? I have a service provider that does stuff(for lack of a better word).

Several functions in that service provider deal with a custom table in the database. Lets assume that in a function an id is passed, if said id doesn't exist I want to stop the process. Throwing out an exception would normally be the way to go, because this is an exceptional situation. The process cannot continue without that information.

I'm not exactly sure how to handle that in Drupal. I don't have that much experience with it.

I noticed that Symfony has an exception handler itself but I'm sure Drupal handles things differently.

Do I log the exception and kill the process? Just throw it out and hope for the best?

Exception handling in Drupal

Exceptions are handled by FinalExceptionSubscriber, unless there is a more specific exception subscriber handling it before.

Core defines several of them, which are listed here: 27 uses of GetResponseForExceptionEvent

How default exceptions are handled

When you throw an exception in code

throw new \exception('ID ' . $id . ' not found in table xyz!');

the default exception handler returns a 500 http status code with this standard message:

  The website encountered an unexpected error. Please try again later.

If you enable error reporting (admin/config/development/logging) you get a more verbose exception message displayed on screen:

  The website encountered an unexpected error. Please try again later.

  Exception: ID abc not found in table xyz! in Drupal\mymodule... (line
  123 of modules/custom/mymodule/src/....php).

Conclusion

Now, what you want to do depends on how much information you want to disclose to the public. Often if you don't find the data you are looking for a 404 exception is more meaningful than a 500 exception. If none of the core exception handling fits your purpose you can implement a custom exception subscriber:

Handle database connection exception via custom handler


How to install oAuth using PHP 7 and PECL OAuth library? I am [unsucessfully] trying to enable the Twitter module on a Drupal 8 site that is using PHP 7 on ubuntu. The Twitter module requries oAuth to work and oAuth requires the PECL OAuth library.

If I run sudo pecl install oauth

I get back:

pecl/oauth is already installed and is the same as the released version 2.0.2 install failed

and then if I try drush en oauth

I get back:

Module oauth doesn't meet the requirements to be enabled.            [error]
OAuth module requires the PECL OAuth library.

Any help with how to configure the oAuth moudle and the PECL oAuth library?

Well, while I have no final solution, since I humbled over the same issue 2 years later today, I can at least put some more light on it and help with some more tests, etc.

First things first: There is some bug tracking missing in your report.

What is php -m saying? It should list all recognized php modules. The pecl php extension oauth should be listed here. If not, check if you carefully followed the instructions printed on the terminal while installing sudo pecl install oauth. It says that you have to make sure that the line  extension=oauth.so is added to your php.ini. This is a standart recommendation which can also be translated to: make sure that oauth.ini is in .../php/mods-available and symlinked from .../apache2/conf.d/... to it to be recognized as a enabled module.

If not then check php-config --extension-dir to see where all your php .so extensions are really installed and then list them with ls -ahl to make sure that oauth has been compiled correctly.

Another thing to be aware of is that php comes in 2 modes: cli mode and server mode. Both can be mixed sometimes and can cause confusion since even Drupal mixes it all the time to check php extensions. Create a simple test.php file and put <? phpinfo(); ?> in it and run it as a local link in browser to check if OAuth is listed there somewhere (CTRL+F oauth). If it is listed it seems that only php cli does not recognize the extension and Drupal cannot find it. In this case repeat the step above (symlink) with the extension also symlinked in .../php/cli/conf.d/.... Then php -m would show the module recognized.

Finally, if you checked it all twice like me and found out that the oauth extension still doesn't load into your php/apache2 enviroment correctly or Drupal won't find it, you will stuck on the same level like me :) And I found out, that I am not allone. There seem to be a list of issues regarding this in the web (Google) OAuth making some trouble under php7.

But if you have checked twice that php AND(!) php-cli can find the module, you will be part of the 99% who made it work with Drupal finally then. Good luck.


user specific menu tab I have a menu tab on nodes which is visible to everyone on the site. But I want it to be user specific. If the logged in user is the one who created that node, only he should be able to see the menu tab. Is it possible to do this using views ?

You can always add access argument "edit own page content" replace page with you content-type name. If you want more complex permissions you can add your own access callback to a menu item which will return true or false. For further information check http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7


Flexslider view with pictures from nodes tagged with a taxonomy term I need to group 10 images (random choice) of nodes belonging to a content type, and belonging to taxonomy foo with the term bar, in a Flexslider. How can I  setup that content pane view ?

Precision : each node can have one up to ten images.

I created a content view,

with that image field
Filtered by content type
Sort criteria : Global Random
Contextual filter : Content : taxonomy foo(provide default value : taxonomy term ID from URL)

If I use format unformatted list / display all items, it gives me a list of expected images. But if I use Flexslider format, it groups all the images of a single node in each slide ! I understand that the query result is grouped by nodes, when I just need its images ...

View preview

I suspect the "Multiple field settings" in the view image field configuration. Try to uncheck "Display all values in the same row".


Stuck developing a new library module for "vminpoly". "Drupal.behaviors" confusion I think this could be really useful to the masses. I've so far not found a alternative. If you know of one, please do advise.

My use case is having a banner with a height of 85% of the viewport. The new vh, vw and vmin length units in CSS are great for this. Except they don't work in all browsers and devices.

The vminpoly library looks like a great solution. At window resize time, it generates CSS code for the 'px' equivalents and appends it in a 'style' element at the end of the 'head' element. The generated code respects media queries.

On their demo the JS part of the source code, in the footer, looks like this:

<script type="text/javascript">
      if (!Array.prototype.filter)
      {
        Array.prototype.filter = function(fun /*, thisp*/)
        {
          var len = this.length;
          if (typeof fun != "function")
            throw new TypeError();

          var res = new Array();
          var thisp = arguments[1];
          for (var i = 0; i < len; i++)
          {
            if (i in this)
            {
              var val = this[i]; // in case fun mutates this
              if (fun.call(thisp, val, i, this))
                res.push(val);
            }
          }

          return res;
        };
      }
    </script>
    <script src="tokenizer.js"></script>
    <script src="parser.js"></script>
    <script src="vminpoly.js"></script>

So being as there isn't much to the module and in the interest of being complete, here are my files:

vminpoly.info

name = Vminpoly
description = Adds the vminpoly javascript plugin. It adds support to allow the use of vw,vh/vmin units in your theme.
core = 7.x
dependencies[] = libraries

vminpoly.module

<?php

/**
 * Implements hook_libraries_info().
 */
function vminpoly_libraries_info() {
  $libraries = array();
  $libraries['vminpoly'] = array(
    'name' => 'Vminpoly',
    'vendor url' => 'https://github.com/saabi/vminpoly',
    'download url' => 'https://github.com/saabi/vminpoly',
    'version callback' => 'short_circuit_version',
    'files' => array(
      'js' => array(
        'tokenizer.js',
        'parser.js',
        'vminpoly.js',
      ),
    ),
  );

  return $libraries;
}

/**
* Short-circuit the version argument.
*/
function short_circuit_version() {
  return TRUE;
}

/**
* Load all files
*/
drupal_add_js('if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; }', array('type' => 'inline'));
$name = 'vminpoly';
libraries_load($name);

I'm sure this will be of help to others, maybe even you.

The question is what is wrong with it. I'm pretty confident (famous last words) that everything is as it should be, except the vminpolydrupal.js file. I'm sure its my lack of understanding when it comes to behaviours and tbh JS generally. I feel as though "context" needs to be added to their code snippet somewhere.

I'm out of my comfort zone and learning. Please help...

So I had a few problems with this. First of all my .module file defined a library because that felt like the proper way to do it. However I received errors in the console and needless to say that it didn't work. After Googling the error I found out that it happens when everything is in the head.

So I removed the library implementation. Then the script itself didn't work. Again after searching on Google I found a fork of it where the guy had fixed those errors. This can be found at: https://github.com/gfaceless/vminpoly

I created a directory called lib, then placed parse-css.js & vminpoly.js in it.

My .module file became:

<?php

/**
* Load all files / JS
*/

drupal_add_js('if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; }', array('type' => 'inline', 'scope' => 'footer'));
drupal_add_js(drupal_get_path('module', 'vminpoly') . '/lib/parse-css.js', array('scope' => 'footer'));
drupal_add_js(drupal_get_path('module', 'vminpoly') . '/lib/vminpoly.js', array('scope' => 'footer'));

Also removed dependencies[] = libraries from the .info. Lastly, for me it didn't kick in unless I aggregated my CSS files.

Hope this helps others. Now my vh, vw and vmin length units work across browsers. Happy days!


Can't create table when installing module I have a simple 'form_example' module and I want to add a database table when instaling module. I created this form_example.install file:

<?php

function form_example_schema() {
    $schema['form_example_table'] = array(
        'description' => 'Table for form_pokus module',
        'fields' => array(
            'id'        => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
            'name'      => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'gender'    => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'message'   => array('type' => 'text', 'not null' => TRUE,   'default'  => ''),
            'status'    => array('type' => 'text', 'not null' => FALSE ),
            'created'   => array('type' => 'int',  'not null' => TRUE,   'default'  => 0),
        ),

        'primary key' => array('id'),

    );

    return $schema;
}

I disabled this module, then deleted it from directory, flushed all chaches and then installed and enabled again this module, now with .install file. But new table is not appearing in database. Im using PostgresSQL. What I am missing?

Follow the standard procedure to unisntall a module.

In short, once the module is disabled it may appear in the Uninstall tab of the modules page. Select the module in that tab and click 'Uninstall'.

When you disable a module its configuration and tables are kept, so if you enable again all data and configuration remains the same. When you uninstall a module you tell Drupal to wipe out any configuration and data by that module. When enabling it again Drupal detects that there's no configuration nor tables of that module and creates them again. If you only disable the module and enable it Drupal doesn't create configuration and tables because they should be in the database,m as Drupal knows module was enabled once.

In module list you have the available modules, some them enabled and some them disabled. If oyu want to comnpletely remove a module you have to disable, uninstall and delete the folder manually.


Can you override single submit forms? I have a form that generates some custom financial reports (can't use Views).  It has some typical form elements, a table of results, and three submit buttons: Submit, Reset, and Download.

Submit and Reset do what you think. Download triggers a submit handler that builds a CSV from the $form['table'] in the handler (which is what the user has generated, and prevents another complicated database query + computations and another route to essentially do the same work), and then spits it out with a $form_state->setResponse($response).  This works great.

I discovered an interesting edge case, though, during testing.

core/misc/form.es6.js has a section of code in it (lines 117-134 in Drupal 8.8.5):

Drupal.behaviors.formSingleSubmit = {
  attach() {
    function onFormSubmit(e) {
      const $form = $(e.currentTarget);
      const formValues = $form.serialize();
      const previousValues = $form.attr('data-drupal-form-submit-last');
      if (previousValues === formValues) {
        e.preventDefault();
      } else {
        $form.attr('data-drupal-form-submit-last', formValues);
      }
    }

    $('body')
      .once('form-single-submit')
      .on('submit.singleSubmit', 'form:not([method~="GET"])', onFormSubmit);
  },
};

This prevents a form from being submitted more than once if it hasn't changed.  However, since my Download button is a submit handler, the above code runs, which then prevents the Reset button from working unless another form element has been changed.

My current workaround is a bit of a sledgehammer:

Drupal.behaviors.sledgehammer = {
  attach: function (context, settings) {
    $('form.my-form', context).on('submit', function (e) {
      var $form = $(e.currentTarget);
      $form.removeAttr('data-drupal-form-submit-last');
    });
  }
};

As far as I can tell this works, but I have BigPipe turned on and am going to AJAX up the form a bit, so I am worried that this may be fragile.

Is there an JS API way to disable the single-submit behavior, or is a workaround the only solution?

If you haven't already, try using button rather than submit type.

'#type' => 'button',

  When the button is pressed, the form will be submitted to Drupal,
  where it is validated and rebuilt. The submit handler is not invoked.

Perhaps this will prevent that formSingleSubmit behavior from running???

If the above doesn't work, since all the formSingleSumit behaviour does is prevent form from being submitted if it hasn't changed and nothing else. Therefore, you don't need this behaviour and since Drupal is global, you could just do in custom.js:

delete Drupal.behaviors.formSingleSubmit;

OR set it/override it to empty

Drupal.behaviors.formSingleSubmit = {};


drush features-list-packages in drupal 8 doesn't include prefix I've just started using Drush and Features with Drupal 8. I'm running into a point of confusion, and I can't figure out if it's a feature or a bug.

In the past our team prefixed all the site-specific features with some abbreviation, let's say, whg_. Then, when I run drush fl the features would show up as whg_calendar, whg_events, etc. It now appears that features automatically appends the bundle's abbreviation to the feature, great.

The issue is when I drush fl I now get a list of features without the abbreviation: calendar, events, etc. I can use the feature commands to update, revert, etc, but I can't use the pm- commands to modify the modules, since, they are in fact, prefixed. So, in order to uninstall the module I have to pm-uninstall whg_calendar.

Additionally, drush fu calendar creates a new feature at modules/custom/calendar

This seems like an inconsistent way to work with features. This might be a meta question, but, is this a bug, should I report it to the github project?

For configuration management in Drupal 8, you don't need to use features, you can use the configuration management module, which outputs .yml files.

The files are saved at sites/default/sync

to export them, use

drush cex

(drush configuration export)

and to import them use

drush cim

You can also manually do this from /admin/config/development/configuration

See https://www.drupal.org/documentation/administer/config


edit form: default value file field On my edit form I need to fill in the file field, this is my current code:

    $form['file'] = array(
    '#title'        => t('Upload image'),
    '#type'         => 'file',
    '#description'  => t('Images must be one of jpg, bmp, gif or png formats.'),
    '#default_value'        => "$link->icon",
    '#ajax'         => array(
      'wrapper'       => 'box',
      'name'          => 'icon2',
    ),
);

but the file field remains empty, in this way the admin has to reselect the desired image each time he edits the entry. The field returns 'no file chosen'.

Any ideas?

Update I

$form['file'] = array(
    '#title'        => t('Upload image'),
    '#type'         => 'managed_file',
    '#description'  => t('Images must be one of jpg, bmp, gif or png formats.'),
    '#default_value' => variable_get('', $fid),
    '#upload_location' => 'public://',
    '#ajax'         => array(
      'wrapper'       => 'box',
      'name'          => 'icon2',
    ),
);

According to the FAPI documentation, #default_value isn't a valid property for a file element which is probably why adding it to the array has no effect.

You might have better luck using a managed file element instead; although the documentation also states that a #default_value is not valid for that type either, I've used it successfully for ages now. The default value needs to be a file id (fid) which references a file in the file_managed table.


Primary admin actions block on view dissapears if change path There is a "primary admin actions" block in the seven theme (provided by the Drupal 8 standard install profile) which only shows up if my view if the path is "admin/content"  but if I change the path to anything else, the block is gone.  where is this configured ?

The LocalActionsBlock is a block plugin that displays menu action links for a given route based on the LocalActionManager::getActionsFromRoute method.

The route that corresponds to the path /admin/content has action links, but whichever route that corresponds to the path you are using does not have any action links defined.

Action links are defined in MODULENAME.links.action.yml file.

If the desired outcome is to have the local actions that correspond to /admin/content on a different path, then a module should be created that defines additional action links for those routes.


Access by role based on term referenced in the node I'd like to restrict access to content based on a term referenced in the node.

For example, I have a content type 'submission' and I want users with the role 'curator' to be only able to view nodes that have the taxonomy term 'art'.

Any pointers towards a sustainable solution to this?

If you're wanting a custom module based solution, Drupal has hook_node_access() which lets any module control access to a certain node. In your case, you want check the $node object on a 'view' $op and return the appropriate NODE_ACCESS_* constant which tells Drupal when the user has access to the node.

// @TODO: Replace 2 with your curator RID.
define('MYMODULE_CURATOR_ROLE_ID', 2);

function MYMODULE_has_terms($node) {
  // @TODO: Define logic that checks if node taxonomy field has certain terms.
  return FALSE;
}

/**
 * Implements hook_node_access().
 */
function test_node_access($node, $op, $account) {

  // Only step in when curators are viewing 'submission' nodes
  // and allow access if a node is tagged with certain terms
  if (is_object($account) && user_has_role(MYMODULE_CURATOR_ROLE_ID, $account) ) {
    if (is_object($node) && $node->type == 'submission' && $op == 'view') {
      return MYMODULE_has_terms($node) ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}


Configure a block view via block settings I'm developing a website for a comprehensive but not professional user. He has the permissions to configure blocks (in order to tweak minor things like ordering or so).
Now I have a block view and I want to allow him to configure the number of displayed items for that block without giving him the permissions for view configuration in general.

Is there a way to put certain aspects of a block view configuration onto the configure block page or a similarly consistent way to achieve that?

(working on drupal 7 with views 3.10, btw.)

Views UI: Edit Basic Settings may meet your needs.

  "Views UI: Edit Basic Settings" places edit tabs on Views pages, similar to node pages, and allows users with the correct permission to modify their header, footer, title, empty text, or number of items to display. This module also provides a separate interface that displays a list of views. All Views are defined by you, so you can exclude certain Views.


How to give anonymous user access in a menu hook? I have a module with a menu hook that I want to give access to everyone. At first I had simply

function hook_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_callback',
  );
  return $items;
}

But when I navigated to /search, I got a warning that I didn't have permission. I thought I had remembered somewhere along the line that I could do 'access callback' => TRUE, in the menu hook to allow anonymous access, but that doesn't seem to work either.

Do I really have to add another function that just returns true to use as the access callback to give anonymous users access to this path?

You can definitely set 'access callback' => TRUE on the menu item and that will bypass any access checks, you don't need to implement a function that just returns TRUE (it would be redundant). Don't forget you need to clear the caches before changes in hook_menu will get picked up though.

Rather than just blindly returning TRUE though it's probably a better idea to assign a permission to the anonymous user role, or piggyback off of one that's already there (access content is the usual suspect for this if it fits in with your workflow). You can do that by using 'access arguments' => array('access content') instead of 'access callback' (don't use both).

Also you've missed out the title in your example, according to the docs that property is required. I doubt that's actually causing the problem though.

Just on another note, you mention that you're visiting '/search' to test this page - the path you've defined will be at '/site_search' instead.


Can I allow users to choose what input widget a Drupal field should use on a node by node basis? This is a question I've asked on Stack Overflow but perhaps this is a better place for it. Apologies if this is seen as cross-posting...

I have a "transcription" field available within a content type in Drupal 7. Is there a way I can add a switch to allow the user to select whether that transcription content should allow tabular data input (via the TableField module) or whether it should be rich text/html?

In your content type definition, create two different fields, eg: data_tab and data_text. Then have a third field where the user can indicate their format, and use the Conditional Fields module to display the correct data input field.


D7: Empty image upload field when adding a translation By default when you add a translation your fields get pre-filled with the content of the original language. Is there a way to stop this behaviour for specific fields, in this case an image field. Both the node and field are set to translatable. The image field still needs to be translatable, but the original content should not get copied into the translation.

Reasoning for this is because on our project we have a master language which will provide default content if no localised content is found. So if we upload an image in the master language en and no image is uploaded for nl we use the image of the en language.

But by default the image is copied into the translation, so if the image needs to be updated for the master language, you then need to re-visit every translation and change the image here as well.

Practical example. I created a node in the language English and uploaded an image for field field_series_image. Now when I add a translation for Dutch when I hit the node/{nid}/edit/add/en/nl page I would like to have an empty image field and not pre-filled with the values from the source language en.

I have tried setting and unsetting a lot of values but none of them seemed to work. I tried to do this in the form_alter hook like this:

my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'my_custom_node_form_id') {
    if (strpos($form['#action'], '/edit/add/') > 0) {
      // Logic went here.
    }
  }
}

Things I have tried:

Unsetting the field in the $form_state['build_info']['args'] array
Unsetting the default value in the $form array
Unsetting the field in the $form['#entity'] array.
Setting the default value to 0 ($form['field_series_image']['nl'][0]['#default_value'] = 0)

None of them seemed to work, maybe because the image field is a widget?

TLDNR;
When adding a translation (so being on node/{nid}/edit/add/en/nl) I want to empty a image field using some hook. So the field is empty on the page and not saved using the values from the original node.

Figured it out after spending about a whole day of trying in the wrong hook.

Turns out you need the hook_field_widget_form_alter for this.

/**
 * Implements hook_field_widget_form_alter();
 */
function my_module_field_widget_form_alter(&$element, &$form_state, &$context) {
  $field_name = isset($element[0]['#field_name']) ? $element[0]['#field_name'] : NULL;
  if ($field_name === 'field_series_image') {
    if (strpos($form_state['complete form']['#action'], '/edit/add/') > 0) {
      // Works for single image fields (product display).
      $element[0]['#default_value']['fid'] = 0;

      // In case we have more images uploaded, unset all.
      for ($index = $element['#file_upload_delta']; $index > 0; $index--) {
        unset($element[$index]);
      }

      // Also reset the upload delta to 0.
      $element['#file_upload_delta'] = 0;
    }
  }
}

Code above suits our needs.


How to duplicate a display (which is not the master) as a different display type? Assume you used Views to build a page display (in Drupal 7). So you have the typical "master", and an additional display called (let's say) "MyPageDisplay". And assume that in this "MyPageDisplay" you "overwritten" various settings (fields, sorting, whatever) from your "master".

And then you want to create a block display that's exactly the same (same filters, etc) as the "MyPageDisplay". There doesn't seem to be any facility to copy or clone such "MyPageDisplay"-display.

How can you duplicate a Views display like "MyPageDisplay" as a different display type in D7? And is there any type of improvement in Drupal 8 about this?

Drupal 7 solution
There is no out-of-the-Views-box solution for this in Drupal 7 ... Except if you get really creative (or via "ugly ways" as @MPD wrote in a comment below the question) with exporting / editing / reimporting such view. But that's not out-of-the-Views-box of course, and  to my knowledge not included somewhere within the Views UI. Comment #1 in the issue about "Clone a Page view into a block view" seems to confirm this.
Drupal 8 solution
In Drupal 8, for an existing display of a view, assuming it's a page display, you can say "duplicate this display as another display type". This will copy all of that view definition to the new display.
As an example, in a standard (core only) Drupal 8 site,  you can now duplicate a page display as:

another page.
a block.
an attachment.
an embed (1).
an entity reference (2).
a feed.

This appears to be one of the most exciting new features of Views in Drupal 8 ... Apart from Views in Drupal Core (= VDC) ... of course.
Notes:

(1): In the Views settings, if you select “Allow embedded displays”, then they can be used in code via views_embed_view().
(2): In the Entity Reference field settings, select “Filter by an entity reference view” and use a view with this display type to define what can be referenced.

Credits: "Babou", who made me discover it while listening to "Talking Drupal (episode 111)".


How do I call legacy PHP files? I am unable to call PHP files inside the Drupal directory. My task is maintaining staff's old pages on the new platform. With pages written on clear HTML, there is no problem: I place files in a folder I created (domain.org/sites/default/files/share/staff_folder).

In sites/default/files/.htaccess I added DirectoryIndex share and now the link to the domain.org/sites/default/files/share/staff_folder/index.html can be used. When I import pages written in PHP, e.g. calling domain.org/sites/default/files/share/staff2_folder/index.php, I get a 403 error:

  Forbidden

  You don't have permission to access /sites/default/files/share/staff2_folder/index.php on this server.

While /sites/default/files/share/staff2_folder/index.html still works.

This is the part of .htaccess, which controls the access to php files:

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

You can see, how the access for statistics.php is allowed. You can add your own rules (at your own risk).


How to list all the user's "member for" via "Views"? In Drupal 8, there is a "member for" in the profile page to show that how long time since this user be a member until now.

I would like to list all the user's "member for" via Views. However there is no such variable in the Views FIELDS.

I was thinking create a user field called "member since" and then every day get the "member for" value (which in the profile already) everyday, and display this "member since" field via Views. However:

I don't know how to get the value of existed "member for" variable in Drupal 8 for created user field "member since". (of course I can calculate it by myself, but I don't want to deal the timestamp, formation etc)
I don't know how to run this function to get the value of existed "member for" variable one time everyday.

Or is there a better way to do it (Note I need to use Views to display it)?

Thanks!

This is quite easy to achieve. Simply add the user's created field to your view, then change the field formatter for this to Time ago.


Custom Webform handler not working on Wizard Webform I am attempting to write a simple webform handler to add to the end of a multi-step webform, ultimately to generate a barcode with the submitted data. I've had success with other handlers on single step forms but it looks like the handler causes the wizard form to freeze and not progress to the next step.
My suspicion is that I'm missing something in my plugin code but I can't seem to find an answer to the problem in similar issues.
So far there's no functionality attempted in the handler because the form freezes on the first step.
Ultimately I only need this handler to fire upon final submission of my form.
I'm trying to test for the forms state with $webform_submission->getState() but I can't seem to get it right
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {

   $state = $webform_submission->getWebform()->getSetting('results_disabled') ? WebformSubmissionInterface::STATE_COMPLETED : $webform_submission->getState();
    if ($this->configuration['states'] && in_array($state, $this->configuration['states'])) {
       //do something

    }
  }

Hopefully this will help someone out there but this is the code I finally got working.  It takes the serial value from a webform submission and writes a Png barcode for use in emails.  I'm using the Barcodes Module for Drupal 8.
use Com\Tecnick\Barcode\Barcode as BarcodeGenerator;

class BarcodeHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   * Write PNG barcode for registration emails
   */
 public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
   $regId = $webform_submission->serial();
   $type = 'C39';
   $barcode_file = 'registration/barcodes/' . $regId . '.png';
   $barcode = new BarcodeGenerator();
   $barcode_obj = $barcode->getBarcodeObj($type, $regId, 250, 50, 'black');

   file_put_contents($barcode_file, $barcode_obj->getPngData());

  }
}


Migrate from Ubercart 3 to Commerce I have been trying to understand how to accomplish this for quite some time.  And I'm not getting anywhere. The info I'm finding seems a bit dated.

Can anyone tell me where to start to get this accomplished?

I am looking to migrate only products.  Nothing else.  The new site will be a fresh start other than product/inventory.  And with some 1500 products, I really need a migration process.

Is there a template for Commerce Ubercart Migration that I am missing?

Thanks.

Our official migration path lives in Commerce Migrate and contains migrations for Commerce 1.x, Ubercart 2.x (D6) and Ubercart 3.x (D7). Improvements are released monthly.


How can I allow the current user to only see their own page? I created a page in a custom module. I want only the current user to access this page on their behalf.
For example, I am using it with ID 51. If I go to :
/user/51/tasks

I can see this page.
If I go on :
/user/78/tasks

I must have an error 403 access denied.
How to do this ?
task_notify.user_page.tasks:
  path: '/user/{user}/tasks'
  defaults:
    _controller: '\Drupal\task_notify\Controller\TaskNotifyUserController::Tasks'
    _title: 'Liste des tâches'
  requirements:
    _permission: 'access content'

UPDATE :
My custom module is here :
https://git.drupalcode.org/sandbox/zenimagine-3076032
I applied kiamlaluno's answer but I have the following error :

/task_notify/src/Controller/TaskNotifyUserController.php
<?php

namespace Drupal\task_notify\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;

class TaskNotifyUserController extends ControllerBase {

  public function Tasks() {
    return [
      '#theme' => 'task_notify_user_template',
    ];
  }

  public function taskAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user->id() == $account->id())
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer users'))
      ->cachePerUser();
  }

}

_permission only allows to give access to the route to the users who have that permission; it doesn't allow to give access basing on more complex conditions, as in the case of this question. As described in Custom route access checking, the route definition should be similar to the following one.
task_notify.user_page.tasks:
  path: '/user/{user}/tasks'
  defaults:
    _controller: '\Drupal\task_notify\Controller\TaskNotifyUserController::tasks'
    _title: 'Tasks list'
  requirements:
    _custom_access:  '\Drupal\task_notify\Controller\TaskNotifyUserController::taskAccess'
    user: \d+

The TaskNotifyUserController class would need to contain at least the following code (and other methods you need from that controller, including tasks()).
class TaskNotifyUserController extends ControllerBase {

  /**
   * Checks access for the users task page.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function taskAccess(UserInterface $user, AccountInterface $account) {
  public function taskAccess(UserInterface $user) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user()->id() == $account->id())
      ->cachePerUser();
  }

}

If then the access to the route should be allowed also to users with a specific permission (for example, the permission to administer users), the taskAccess() code would be similar to the following one.
  /**
   * Checks access for the users task page.
   *
  /**
   * Checks access for the tasks tab.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function taskAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user->id() == $account->id())
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer users'))
      ->cachePerUser();
  }

Don't forget to import the class used from the controller, adding the following lines at the top of the controller file.
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;

If the controller class uses other classes from different namespaces, similar lines must be added for each class.
I took the code used from Drupal core for the Tracker module as example. The Tracker module shows its tracker page on /activity/{user} using a controller to render it. See TrackerController.php.
  /**
   * Checks access for the users recent content tracker page.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   The access result.
   */
  public function checkAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user
      ->id() == $account->id())->cachePerUser();
  }

The custom access callback is defined in tracker.routing.yml.
tracker.users_recent_content:
  path: '/activity/{user}'
  defaults:
    _controller: '\Drupal\tracker\Controller\TrackerController::buildContent'
    _title: 'My recent content'
  requirements:
    _permission: 'access content'
    _custom_access: '\Drupal\tracker\Controller\TrackerController::checkAccess'
    user: \d+


Previewable email templates token replacement From my form_alter code, I would like to redirect to email template (Previewable email templates)

$form_state['redirect'] = url('pet/email_template', $options )
The params are set as
$options = array(
      'absolute' => TRUE,
      'query' => array('nid' => '1','uid' => '3')
  );

In the email template, there are tokens [webform:sid] and [webform:data]. How do I replace those data [webform:??] by using the url call to template?
Thank you.

Put the token [webform:sid] in template

Use
function mymodule_pet_substitutions_alter(&$substitutions, $params) {
$substitutions['webform'] = array('sid'=> {value});
}


How can I search internal blocks in the admin section? I've inherited a very large site that I didn't build. I am trying to find one particular block amid around a hundred - I'd like to search these blocks for some of the specific HTML classes they contain to edit them.

It looks like https://www.drupal.org/project/block_search isn't up to date anymore - is there a convenient way to search the admin section of a drupal site?

If the block you're looking for is a "custom block", i.e. one that you create via structure->blocks->Add block rather than one defined in a module then you should be able to query the database for it like this:

SELECT * FROM block_custom WHERE body like '%my-class%'

...changing "my-class" as appropriate.

Alternatively, you can inspect the markup of the block on the front end and look for a class such as block-123, then navigate to /admin/structure/block/manage/block/123/configure, replacing 123 with whichever block number you found.

If there's no body field on that page then it's probably a block defined by a module.  Then you can try to find a clue as to where it's defined in the classes on the contents of the block, for example if you see lots of classes with the word views in it then it will be a block defined in views and you should look in the views UI to find where it's defined.

Also, turning on the core contextual links module may help as well.

n.b. All this is based on the assumption that we're talking about Drupal 7.  Much of it applies for other versions with some tweaking.


Altering nodes title value I am trying to alter the title of my nodes to prevent URLS appearing in any title. This is the code I am using.

function mytemplate_preprocess_node(&$variables) {
  $node = $variables['node '];
  $variables['title'] = cleaner(check_plain($node->title));
}

cleaner() removes URLs from nodes. The above works perfectly on teasers, but not on full view or when the title is displayed in a list with other articles inside a block.

How can I make sure that the URL disappear whenever the concerned node's title is listed?

You need to implement both

template_preprocess_page() : this will take care of node full view mode.
temaplte_proprocess_node() : this will take care of node teaser view mode

In your theme template.php

function mythemename_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your content type") {
    drupal_set_title("your_title");
  }
}

/**
 * Override or insert variables into the node template.
 */
function mythemename_preprocess_node(&$variables) {
  if($variables['type'] == "your content type") {
    $variables['title'] = "your title";
  }
}

Note:

  only changing in template_preprocess_node(), will now reflect on node teaser view as it will be overridden by page template.
  in order to change  you should use drupal_set_title() instead of $variables['title'].


How to drupal_add_js an external and defer script I've spent quite some time on drupal_add_js and didn't manage to solve this. How can I load an external JavaScript script which will also have the defer attribute?

I want to use this type of syntax:

drupal_add_js('http://example.com/whatever.js', 'external');

But it only produces:

<script src="http://example.com/whatever.js"></script>

I want the end HTML to be:

<script defer="defer" src="http://example.com/whatever.js"></script>

Just add a value in $options

$options = array(
  'type' => 'external',
  'defer' => TRUE,
);
drupal_add_js('http://example.com/whatever.js', $options);

From the documentation:

  Parameters

  $options: (optional) A string defining the type of JavaScript that is being added in the $data parameter ('file'/'setting'/'inline'/'external'), or an associative array. JavaScript settings should always pass the string 'setting' only. Other types can have the following elements in the array:

  type: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults to 'file'.
  ...
  defer: If set to TRUE, the defer attribute is set on the  tag. Defaults to FALSE.


how i can create pages dynamically on users any action? I want a page creation(dynamically), if user uplooads a design(image) which is (or its info) goes to database. The page name should be on the name of design. How can i do this?

Update:
Designs(dress designs[images] ) are submitted by the users through an application which resides on the root of drupal. Not a module of drupal. As the designs are submitted, they goes to a folder at root and relative info goes to drupal database. As i am using drupal bootstrap to get user info and a little more.
So i need a module which listens the request from application(may listen from database updation) and make page of that design with unique path.
Please guide me how to handel this situation

any hint/help is appreciated

this is how one can do so.
First make a content type (also can use Basic Page type).
Then the below code will make pages(nodes of the content type) dynamically.

<?php
// Construct the new node object.
$node = new stdClass();

// Your script will probably pull this information from a database.
$node->title = "My imported node";
$node->body = "The body of my imported node.\n\nAdditional Information";
$node->type = 'mynewpage';   // Your specified content type
$node->created = time();
$node->changed = $node->created;
$node->status = 1;
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;       // Filtered HTML
$node->uid = 1;          // UID of content owner
$node->language = 'en';
// If known, the taxonomy TID values can be added as an array.
$node->taxonomy = array(2,3,1,);

node_save($node);
?>

if you need to create nodes at root of Drupal directory you also need to include these lines in start of the code

// Bootstrap Drupal
require 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Add multi-level taxonomy term selection field with multiple selection for last level I want to add field with taxonomy term selection
If suppose I have vocabulary as Food and it has hierarchy of terms like below:

Fruit
- Mango
- Apple
- Banana
Vegetables
- Spinach
- Potato
- Tomato

While selecting taxonomy terms in a node I want to first select Fruit or Vegetables and after that another select list should appear with provision to select multiple sub terms for respective top level terms

Example: If I select Fruit from first select list only single selection allowed and then second select list should appear with Mango, Apple, Banana so one should have chance to select multiple fruits from second select list

I tried simple hierarchical select but it doesn't give provision to select multiple terms on last level field.

Have a look at Taxonomy Term Reference Tree Widget module. This does exactly what you need as per its documentation.

Edit: Since now I bettter understand your requirement, you might want to try Hierarchical Select.


Cloned Sites and Original Site Are All Affecting Each Other I am using Aegir to clone my Drupal 7 sites. I don't have any caching enabled on the original site.

When I clone the site everything appears to work correctly, however changes to the drupal database are mirrored between all my sites. For example, adding a new user will add the user to all the sites.

I have verified that separate databases are specified for each of the sites.

Any ideas what would be causing this?

I just figured it out. I have a wildcard SSL setup for my server. By default when you clone a site in Aegir it does not set it up as SSL. However, I was still able to access the cloned site via HTTPS.

The issue was caused by accessing the site via HTTPS when SSL was not enabled in Aegir for that specific site.

As soon as I enabled SSL for the site in Aegir the problem went away.

I'm not exactly sure what was going on in the backend. It would be great if someone could chime in on that...


Remove choice for user delete from Roles which can adminster the Users I have a User Role called Supervisor which can create new accounts of role Supervisor.

The Supervisor can also delete other users with supervisor role. While deleting Other users the Supervisor gets the 4 choices that Drupal comes standard with:-

However, I want to present the Supervisor only the first option:-
 Disable the account and keep its content
and other options to be hidden or disabled by default.

I'd be very thankful for any hints how to achieve that... I'm already using Role Delegation module and have been trying different settings, looks like its not possible via that module.

I would start by creating a custom module and try using hook_form_alter.

function MYMODULE_form_alter(&$form, $form_state, $form_id)  {
  switch ($form_id)  {
    case 'user-multiple-cancel-confirm':
        // ALTER STUFF.. user dsm($form) to show available fields.
        break;
   }
}

Using

global $user;
$roles = $user->roles; // Array with user assigned roles

you can check the array for the Supervisor role.


Spam filter in signatures? Since otherwise great spam module does not check user signatures for spam, I have hard times fighting spammers who just put their spam links in their signatures in the forum so basically they rendered my custom spam filters useless.

I appreciate if you have some suggestions to resolve this problem.

OK, a better answer in the context of forum signatures only ( assuming D6 forum_signature module ) could be

Preprocess the signature.tpl.php template file and add the spam check

in template.php, function sig might be THEME_preprocess_signature, so try both, if first doesn't work.

function THEME_preprocess_signature_forum(&$variables){
  $content = $variables['signature'];
  $test = spam_content_is_spam($content, 'signature_forum');
  if (!empty($test['is_spam']) && $test['is_spam']){
   $variables['signature'] = t('This signature has been removed by our spam filter, please contact the site administrator for assistance');
  }

}

Then clear theme registry cache.

I don't use those modules myself, but such an approach, with a little tweaking, could work.


How to search for content from the Content Management admin view? This feels like such a dumb question to ask, but I can't find a way to search for my content on the Content Management view in the Administration area!

Could somebody point me in the right direction, please?

In drupal 7 you can use the Aministration Views.

It uses the Views module and VBO to create some views to replace all the pages in administrtion area that does some kind of listing.

After the instalation you need enable the views created by this module.

For me this was the only way to get a "Title filter" for the contents in the drupal administration area.


Can entities as users exist without being tied to nodes Can entities as users exist without being tied to nodes, I'm starting a site that I don't want a lot of overhead and it will have a lot of users and they will be contacting each other often.

In D7 Users are an Entity type, they are their own Entity type. A Node is another entity type with various bundles such as Page, Article, etc.

Taxonomy is another example of an Entity.

An Entity does not necessarily mean a "Node" in drupal 7.

See this introduction to Drupal 7 Entities on drupal.org


Change drush language Suddenly my drush has switched language and displays error messages in my native language, which is unfortunately not convenient if one tries to search for solutions on these errors.

Do you know how to switch the language of drush errors back to English?

Adding the following string to drushrc.php worked for me with Drush 5.4:

$options['variables']['language_default']->language = 'en';

In my setup I placed drushrc.php into sites/default/drushrc.php, for other possible locations see documentation in examples/example.drushrc.php in Drush installation directory.


Pulling capacity and slots left from entity registration I'd like to pull the values for capacity and the slots left from a registration created by the entity registration module. This sets up registration entities which are attached to (I believe this is how it works - my familiarity with the entity system is only so-so at this point, but I'm actively learning) nodes.

I'm creating a view for the event nodes, I would like to display these fields - how would I go about doing that? Would I create a relationship of some sort in the view?

What's the standard method to pull another, related entity's content into a node entity?

I managed to solve this by pulling in the relationship of "Registration Settings: Node to Registration Settings" and putting the fields for total as well as used slots in.

In addition, when needing to calculate the amount of remaining slots, I calculated this with views php.


hook_views_post_execute() don't work on AJAX View with exposed filters after 1st refresh I have a View which returns 5 entities of the same type. AJAX - enabled, filters and exposed filters, all working fine.

I need to add a new result, a user - defined entity, at the top of the View results. This programmatically added row should not be affected when the exposed filters are used and should remain at the top of the View, on top of the other 5 returned results, no matter what.

I managed to add this with hook_views_post_execute() but when I use the exposed filters the View returns to its original results and my addition is lost, because AJAX is enabled on this View. hook_views_post_execute() doesn't seem to have any effect after the initial page load.

What is a good alternative for this scenario ie alter the View in a way that's not affected by the AJAX refresh?

When checking the current route match in a Views Ajax request you get the route of the Views Ajax endpoint views/ajax and not the route of the page where the View is placed on.

However, Ajax requests contain the original path of the View and ViewAjaxController::ajaxView() puts this path in the global current path stack (for the pager to work correctly).

So if the path is no longer in the request

$path = \Drupal::request()->request->get('view_path');

it should be transfered to:

$path = \Drupal::service('path.current')->getPath();

Which should then point to the node route you are looking for.


Views contextual filter I really would need some help with contextual filter.

I have a content type I use for products, different kind of security cabinets. In this particulary case it is aboyt burglary safes. They have a classification of 0,1,2,3,4,5, S1 or S2. So all burglary safes has one of these classes. To give them the class I have created a Vocabulary with the name "Burglary Classes" and there I have created the classes 0,1,2,3,4,5, S1 or S2 as terms.

In Views I have made a block with a table presenting all burglary safes, containg fields like dimensons and weight and so on and have brought in this table block to the Content type, as a field, and it works just fine.

Now to my question;
All products in the Content type are not burglary safes so some are not classified according to 0,1,2,3,4,5, S1 or S2 , but I can't firgure out how to configure the Contextual filter.

I want ALL safes classifed to ANY of the terms 0,1,2,3,4,5, S1 or S2 to appear in ALL of the nodes having ANY of the terms 0,1,2,3,4,5, S1 or S2 but NOT to appear in any other node

The best shot I have had is filtering so that in the node only products belonging to the same Burglary Class as the node itself, appears. But as said, I want all products with a burglary class to appear.

Greatful for your help

Hans

(On request I have tagged the question for Drupal 7! Sorry for forgetting)

Have you looked at the PHP filter module? I believe you could make two views, one which displays the burglary safe items and one which displays the non-burglary safes. Add both blocks to all pages, then use the filter module with a PHP expression to decide which to make visible and which invisible.


How to know if who created the order Is it possible to determine who created the order? I've installed the entity reference module, then added a entity reference field in the order, but I'm not sure if this will work.

I've used the hook_form_alter() to get the current user id and set the current username as a default value.

How to check and save the current user who created the order upon saving the order? Will only set the default value on first save, then it won't change anymore in the next save.

Below is my code:

$user = $GLOBALS['user'];
if ($user->uid) {
  $form['field_order_created_by'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $user->name;
}

What you can do is you can create a small table which keeps your order id, user id and anything else you want. Whenever the order is saved you can check whether a record exists for the particular order id. If there is no you add the record otherwise you don't change the current record.
For that you can use hook_commerce_order_presave(). Inside this hook you can use your code l

option 1

function yourmodule_commerce_order_presave($order){
    if(!db_result(db_query('SELECT * FROM {your_table} WHERE orderid = %d', $order->id)))
        $user = $GLOBALS['user'];
        if ($user->uid) {
            $form['field_order_created_by'][LANGUAGE_NONE][0]['target_id']['#default_value'] =       $user->name;

        //add new record to yuor table
    }

}

option 2

function yourmodule_commerce_order_presave($order){
    if(!check_record_exists($order->id))
        $user = $GLOBALS['user'];
        if ($user->uid) {
        $form['field_order_created_by'][LANGUAGE_NONE][0]['target_id']['#default_value'] =       $user->name;
    //add new record to your table
}

function check_record_exists($oid){
    $exists = db_result(db_query('SELECT * FROM {your_table} WHERE orderid = %d', $oid));
}


How do I disable the default user system or view pages without login? I apologize in advance if I haven't used the proper terminology, but I am very new to working with any CMS, let alone Drupal.

Now... On to the question...

On the  page, I have a block that explains the purpose of the site, and everything looks fine when I'm signed in, however, once I sign out, I get "Access Denied" on all of my pages & subpages.

For the website I'm building, I have absolutely no need for a user/authentication system at this time.

How can I disable the user framework, or how can I make all pages visible without having people log in?

Again, sorry for the likely improper terminology... Thanks in advance for your time & help.

It depends on the type of page really, what module provides it, how permissions are implemented by that module - the short answer is by setting correct permissions at /admin/people/permissions.

You can't disable the user module, it's a required part of Drupal. Conceptually, if you were to disable it you'd have no authentication control over the admin section, and any user could make whatever changes they wanted - obviously that's not a situation that can be allowed to exist for 99.99% of users. And if you do want that, you just need to set up permissions to allow it.

But you can stop users from registering, which avoids that problem. And by setting appropriate permissions you can decide exactly what users (or even groups of users, using the Roles system) can see/do.


Is there a way to schedule Automatic Source Code and Database Backups? A colleague told me about a plugin that he used to run on Word Press that would save his Source Code and DB automatically. He asked me to look into any plugins like this for Drupal 6.x and 7.x.

Does anyone have any experience with this that they can share?

Thanks,

You can use Backup and Migrate module. It is available for both, Drupal 6 and 7.

  Back up and restore your Drupal MySQL database, code, and files or
  migrate a site between environments. Backup and Migrate supports gzip,
  bzip and zip compression as well as automatic scheduled backups.


Drupal blocks not showing up I am editing a site someone else built for my small nonprofit organization, and as you will see, I know very little about working with drupal (or anything beyond basic HTML, really.) I apologize in advance for that and will be so appreciative if anyone can help me.

I am trying to fix a problem. I am trying to add a listed page to a block, and the block is now not showing up on any pages it was previously associated with. When I went into a different block and tried to add a page, that block also stopped showing up. (You can see an example here: http://africaid.com/upcomingevents -- the left hand side block has disappeared.)

I am wondering if the problem is related to two warning messages. The first, on the "Administer" home page, says "One or more problems were detected with your Drupal installation. Check the status report for more information."

When I go to list content, I get the following message:

strict warning: Non-static method view::load() should not be called statically in /home/africaid/public_html/sites/all/modules/views/views.module on line 843.
strict warning: Declaration of views_plugin_display::options_validate() should be compatible with views_plugin::options_validate(&$form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/plugins/views_plugin_display.inc on line 1877.
strict warning: Declaration of views_plugin_display_page::options_submit() should be compatible with views_plugin_display::options_submit(&$form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/plugins/views_plugin_display_page.inc on line 481.
strict warning: Declaration of views_handler_field_broken::ui_name() should be compatible with views_handler::ui_name($short = false) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_field.inc on line 641.
strict warning: Declaration of views_handler_field_user::init() should be compatible with views_handler_field::init(&$view, $options) in /home/africaid/public_html/sites/all/modules/views/modules/user/views_handler_field_user.inc on line 48.
strict warning: Declaration of views_handler_sort_broken::ui_name() should be compatible with views_handler::ui_name($short = false) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_sort.inc on line 82.
strict warning: Declaration of views_handler_filter::options_validate() should be compatible with views_handler::options_validate($form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_filter.inc on line 585.
strict warning: Declaration of views_handler_filter::options_submit() should be compatible with views_handler::options_submit($form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_filter.inc on line 585.
strict warning: Declaration of views_handler_filter_broken::ui_name() should be compatible with views_handler::ui_name($short = false) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_filter.inc on line 609.
strict warning: Declaration of views_handler_filter_boolean_operator::value_validate() should be compatible with views_handler_filter::value_validate($form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_filter_boolean_operator.inc on line 128.
strict warning: Declaration of views_bulk_operations_plugin_style::options() should be compatible with views_object::options() in /home/africaid/public_html/sites/all/modules/views_bulk_operations/views_bulk_operations_plugin_style.inc on line 280.

If anybody can help me with this, I will be grateful for eternity.

Thank you,
Ashley

I'm making a few assumptions, the main one being that you're using Drupal 6...

Basically your PHP error reporting settings include E_STRICT compliance, and the code in the version of Views you've got installed isn't compatible with it. D6, and subsequently the associated version of Views, was written for PHP4 and PHP5, and as such isn't compatible with E_STRICT.

You can either

Disable E_STRICT error reporting in your php.ini/other php conf file (if you're not sure how to do this, get whoever administers your server to do it - it'll make sense to them). Or
Apply the patch in this issue (comment #11) which will remove the problems for PHP5.3. If you have PHP5.4 installed, there's another patch in #26 to apply too.


How can I edit all nodes of thier dates at once? Is there a module that allows me to change the dates of all nodes at once instead of doing it one by one thanks.

In this case, you could update the field in the db, much faster than node_loading and saving all the nodes with batch update etc.. backup db first.

Fields are:

node.created
node.changed
node_revision.timestamp (same as node changed)

e.g

$created = strtotime('2013-01-01 00:00:00');
$changed = REQUEST_TIME; // now

$query = db_update('node');
$query->fields(array('created' => $created, 'changed' => $changed));
$updated = $query->execute();

$query = db_update('node_revision');
$query->fields(array('timestamp' => $changed));
$updated = $query->execute();

drupal_flush_all_caches(); // clear cache


Connecting to multiple databases of different type for form submission I'm developing a GIS mapping system and for that I am using pgSQL, however I am bounded to using mysql for the drupal install because we use Drupal 6 mulitsites using mysql already.  I know I can get around this problem by hard coding using php, html to create my forms that submit to this. I know from Drupal Community Documentation this is not possible as standard. Is it possible via any other method to utilise the Form API and submit to an external DB in a different structure such as pgsql? or do i continue coding my forms by hand for each node?

The example below is exactly what I would like to do however it is clearly shown in the link above that this will not work.

// ... header of the settings.php file

$db_url = array (
"default" => "mysql://user:pass@host/db",
"second" => "pgsql://user:pass@host/db"
);

The code below is from the Form API getting started doc, however it doesnt specify the databse it is actually connecting to?

function test_myform_submit($form, &$form_state) {
 db_query("INSERT INTO {table} (name, log, hidden) VALUES ('%s', %d, '%s')",
   $form_state['values']['name'],
   $form_state['values']['access']['log'],
   $form_state['values']['hidden']);
drupal_set_message(t('Your form has been saved.'));
}

In Drupal 6 you cannot use more than one database engine with Drupal's functions. If you are using MySQL as Drupal storage, to connect to PostgreSQL you need to directly call PDO:

try {
  $dbh = new PDO('pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass');
} catch (PDOException $e) {
  watchdog("your module name",
           "PDO error: %error",
           array("%error" => $e->getMessage() ),
           WATCHDOG_ERROR);
}

Then use your handler just as you would in any non-Drupal PHP code, preferably with prepared statements.


Assign new customer with specific user role upon checkout registration When a new customer is created, in the first checkout steps, its useful to be able to assign him with a specific user role, apart from the default 'authenticated'

A relevant use case would be when there are both customers and different backend user roles (editors e.t.c.) and it is need to create specific permissions to users according to whether they are customers or not.

This has been answered for commerce v1 (drupal 7) in the following
Drupal Commerce assign role on account create on checkout

This solution can be applied to Drupal 8 commerce v2. So by utilizing hook_user_insert one can get the new account and assign it other roles, upon registration.

However its not clear how/if we can determine in this hook whether this new user is a commerce created user and therefore a customer, or if its a user created by the admin and therefore possibly not a customer.

One not so safe condition would be to check if he already is assigned with any roles, as it would be the case if he was a backend user, but still this does not feel so safe.

So, there are 2 questions

Is there a 'by the book' way to assign a specific role to a commerce customer?
Is there a safe way to identify who is creating (commerce checkout or backend admin) a user in hook_user_insert?

Surely If someone creates the order the the order is associated to that user, so in this case you don't need to wory about user being created, what you can do is look in to:

hook_ENTITY_TYPE_update()

this way your going from the order status being upgraded to paid or whatever I dont know what the entity name for the order is but you could grab that loaded it, get the user id and check the roles , if no role add new role to them and save. as a bonus you have more control over what type of products to restrict it to ect.


Unable to retrieve uploaded file in submit handler I'm creating a custom form with a file upload field that will have its contents read, processed then sent to an external API. The problem is whenever I upload the file the field for it appears to be empty in the submit handler and I cannot see why.

In this example I'm using it as an unmanaged file as I only need to process it then remove it but I have tried it as a managed file which does upload (I can see it in the directory) and has the file added to the file_managed database table. I'm not sure where unmanaged file are meant to go to check for their upload.

public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [
      '#attributes' => ['enctype' => 'multipart/form-data'],
    ];

    $form['file_upload_details'] = [
      '#markup' => "<strong>" . $this->t('The KML File') . "</strong>",
    ];

    $form['my_file'] = [
      '#type' => 'file',
      '#description' => $this->t('KML format only'),
      '#upload_location' => 'public://my_files/',
      '#upload_validators' => [
        'file_validate_extensions' => ['kml'],
      ],
    ];

    $form_build = parent::buildForm($form, $form_state);

    return $form_build;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $messenger = parent::messenger();

var_dump(
  $form_state->getStorage(), // Empty array
  $form_state->getValue('my_file') // Empty string
);
  }

All what '#type' => 'file' form elements do is to provide a bare <input type="file"> element. You get a prompt to select a file from your machine and on form submit the browser sends a request to your server, server forwards it to PHP, PHP extracts the file from the request, PHP stores it to the server's temp dir and when the script ends it deletes it again. Not much Drupal involved.

If you need to handle the file somehow and be it just the filename you need to take care of it yourself. And that's what file_save_upload() is for. It expects the $form_field_name as first parameter. And it will return you the file information. When scanning core for '#type' => 'file' you will often see this function being used in the form validation handler. Where the return value is being passed back to $form_state. For example in \Drupal\system\Form\ThemeSettingsForm::validateForm(). Just this time the function is wrapped from _file_save_upload_from_form() to allow correct error handling in forms.

// Check for a new uploaded logo.
if (isset($form['logo'])) {
  $file = _file_save_upload_from_form($form['logo']['settings']['logo_upload'], $form_state, 0);
  if ($file) {
    // Put the temporary file in form_values so we can save it on submit.
    $form_state->setValue('logo_upload', $file);
  }
}


Theming a custom menu block in Drupal 7 So I created a custom menu through the Drupal administration and named it "More Menu." Its machine name, menu-more-menu, was auto-generated by Drupal.

Creating this menu automatically created its corresponding block, and its now available under Blocks administration as More Menu. I then enabled the block and placed it under my desired Region.

I wanted to theme the output of this block. I tried creating a template by following the template suggestion as described here, block--module--delta.tpl.php.

The template file I created was named block--menu--menu-more-menu.tpl.php.

It doesn't seem to work, and I still cannot override it.

Am I missing something?

For custom menu blocks the format for the block template file name is

block--menu--<menu_machine_name>.tpl.php

Note: All machine names begin with the 'menu_' prefix and all hyphens are converted to underscores.


Programmatically get field values of fields added to custom entity I created a custom entity in Drupal 8, and I added base fields.

I add the getter/setter functions to my entity definition file.
They return NULL when called from a preprocess function. (I'm trying to add some variables for the Twig template.)

Why would this be?  I'm using the following code.

public function getProjectId() {
    return $this->get('project_id')->value;
}

project_id is en entity reference field.

The column for an entity reference field is target_id, so you should just need to replace the getter with:

public function getProjectId() {
    return $this->get('project_id')->target_id;
}


Trying to turn on theme debug, but getting an error: Drush command terminated abnormally due to an unrecoverable error I'm new to Drupal and Drush and so am hoping someone can shed some light on this.

I tried to turn on Theme Debug with Drush:

drush vset theme_debug 1

But I keep getting an error I don't entirely understand:

Drush command terminated abnormally due to an unrecoverable error.
Error: Declaration of Drush\Command\DrushInputAdapter::hasParameterOption() must be compatible with
Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in
phar:///usr/local/bin/drush/lib/Drush/Command/DrushInputAdapter.php, line 27

I tried drush status too and got the same issue, so I think drush is probably broken across the board.

I tried deleting and reinstalling drush and reprovisioning my virtual box to no affect.

Would anyone know what could've gone wrong here?

(I am running Drush 8.1.7. on Drupal 7.5)

Update drush

composer require drush/drush:9.0.0-alpha1


Access A Referenced Node's Fields - Field Level Templating I have a content type with a reference field to another content type. This allows an unlimited amount of entries.

I've created a template for this field:
field--node--field-my-fields.html.twig

I want to be able to access the fields of my referenced node. Usually you can do this by accessing the entity, but I can't seem to do this.

{% for item in items %}
  {{ kint(item.content) }}
{% endfor %}

I feel like this should be really simple, but I just can't find a way to get access to the fields!

Thanks in advance for any answers.

In item.content is a render array and usually you can access a referenced entity in a '#' key (for most display settings):

{{ item.content['#node'].field_name.value }}

Field Object

Another way to get the field values is using the field object in element['#items'] and loop through the FieldItemList:

{% for item in element['#items'] %}
    {{ item.entity.field_name.value }}
{% endfor %}

Then you are independent from the display settings of the field.

For background information see this blog post from Berdir https://www.md-systems.ch/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig for the difference between formatted output and the underlying objects. In a field template you don't need to go back to the parent node object, because you can access directly the field object. You can get the parent node from element['#object'] though, if you want to access other fields.


render call in hook_node_presave uses admin theme I am using hook_node_presave() to render my node and then save the output to a field field_node_cache.  However, when I do this, the renderer uses the admin theme, whereas I would like to use the site's main theme.

Is there a way to force it to use the site's main theme without disabling the admin theme?

function MYMODULE_node_presave(NodeInterface $entity) {
  switch ($entity->getType()) {
    case 'MY_CONTENT_TYPE':
      $render_controller = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
      $render_output = $render_controller->view($entity, 'MY_VIEW_MODE', 'ja');
      $html = \Drupal::service('renderer')->renderPlain($render_output);

      $entity->set('field_text_main_display', $html);
      $entity->field_node_cache->format = 'MY_FORMAT';
    break;
  }
}

One way to work around this is to go to /admin/appearance and uncheck Use the administration theme when editing or creating content.

Alternately, you can create a separate user account that does not have permission View the administration theme and use that account to create content.


D7: Resetting ALL user fields (Boolean) at once In a nutshell, I'm trying to stop my users from getting e-mailed more than once per day.

I have some rules set up that will e-mail users when content particular to them is updated.
I have added a Boolean field to user profiles that starts off 'checked' (1) - indicating they have not (yet) been emailed today.

Any rules that e-mail users will first check this user profile value and proceed only if they haven't been e-mailed (field value is 1), but then set this Boolean value to 0 using set a data value in Actions - thus they won't get e-mailed again until the value is changed.

What's the best/easiest way to 'reset' that field in ALL user profiles periodically? (probably once a day)

i.e. at 10:00PM set the boolean field "field_user_not_emailed_today" for ALL users to 1. (checked)

I've seen VBO recommendations for this sort of thing, but seems unnecesary given the ALL users thing.  Is there perhaps a PHP snippet I could call in Rules that would do the trick?

Thanks!

The Rules Once per Day module provides a 'Once per day' rules event that you can use to trigger your boolean flag update.

For bulk updating a list of users, if you have an action that loads a list of users you can then loop through and act on those users with rules.

There are a number of ways you can load a list of users in rules. Some of them are:

The Views Bulk Operations module provides some actions including 'Load a list of entity objects from a VBO view'
The Views Rules module provides the 'Collect view result rows' action.
The Rules Bonus Pack module provides a number of actions, including 'Load a user list with Views'.
You can create a custom action of your own via a custom module. See the rules developer documentation and various blog posts for more details.

I'm not sure of any easier way to loop through all users in the system, but the views approach is fairly straight forward and low maintenance anyway.

Also, you might not always want to loop through all users. for example you might want to exclude administrators or only loop through users where your boolean field is set to 1, to avoid unnecessary processing in the case that not all users have been set to 1 for whatever reason.

The action you use to load the users will create a new variable (eg. 'entity-list') that will be available in future actions. You can then use the 'Add loop' option in the rules actions section to loop through that new variable. That loop will create another new variable for the current item (eg. 'list-item') your are looping over and then you can add actions that act on that variable (eg. data set on list-item:field-user-not-emailed-today).


Workflow - Accepting/rejecting individual changes Is there a way to accept/reject individual changes in the workflow process? If so, how and/or what modules are the best to do this?

I've had frustration with the Workflow module. You may want to try out the Workbench and Workbench Moderation modules. Throw in the Trigger module to send e-mail notifications when a document changes workflow state.


How to create a module to process AJAX request? I want to create a module to process some AJAX request like this:

$.ajax({
    url:'/?q=mymodule/path',
    dataType:'json',
    type:'POST',
    data:{'key':'abc', 'value':'123'},
    success:function(data){
        /*do somthing*/
    },
    error:function(){
        /*do somthing*/
    }
});

So which hook function should I implement?

If you are tying your functionality to Drupal, use Ajax framework commands
.

If you want to process any arbitrary incoming request, (ajax or otherwise) implement a Services resource.


How to block temporarily comments from specific IP address? Can we block specific IP address for a period of time and block posting comments from that IP address for this period of time?
Only posting comments, not viewing pages.

I have not used this module but you can check Comment IP module.

  This module displays a comments IP address in the comment overview
  page and allows you the option to "Delete the selected comments and
  block their IP's" from the comment overview dropdown list.


Missing edit tabs on only one content type I have a custom node template for a particular content type, and it seems that the "view" and "edit" tabs are missing on nodes of that type. However, it doesn't appear that the node templates typically have accesss to the $tabs array; that seems to be something that goes in page.tpl.php (which I haven't overridden or altered). It still work for other node types though, so it must be something in the node template.

When I add a dsm($tabs); to the page.tpl.php and view a node of my custom type, it displays the arrays containing the info for the tabs, so it can't be that my user doesn't have permission, or the tabs wouldn't load any info at all, right?

What should I do to my node template to fix this?

If you have a dsm($tabs) at the top of your page.tpl.php and it's showing it's set, nothing should be unsetting it by the time it is output later on in the template.

For example, in the default D6 page.tpl.php, it does this...

<?php if (!empty($tabs)): ?>
<?php print $tabs; ?>
<?php endif; ?>

and in D7 it does this...

<?php if ($tabs): ?>
<?php print render($tabs); ?>
<?php endif; ?>

...so, I'd take a look at the page source and see if css or something else is causing it to be hidden. For example, perhaps your theme is doing stuff like cascading a class in the body with the tabs class.


List of template suggestion used for a node I'm building a module that return you an HTML styled node via ajax but I have a question.
I want to add a node suggestion only for this module. How?

So drupal have to check:
Exist [in active theme] ajaxnode.tpl? And ajaxnode--nodetype.tpl? If they don't exist choice the normal drupal suggestion template and render the node.

How can i do this correctly?

I'd go and get the Theme developer module.  Simply get the element you want to theme and click on it - then you'll get a list of any template files and/or theme functions that were called in the processing of the element you clicked.

  Firebug for Drupal themeing. See the screenshot and screencast. Note
  that this module injects markers into the DOM to do its magic. This
  may cause some themes to behave erratically and less capable browsers
  may make it worse (especially IE)/. Enable it when needed, and disable
  it afterwards.


Fatal error: Cannot redeclare casa_views_post_execute I understand this to be two declarations of the same function, which is not allowed. But how to fix this?

Everything was fine until I started to enable the MailChimp module, then the backend has this fatal error:

Fatal error: Cannot redeclare casa_views_post_execute() (previously declared in /home/kansascasa/public_html/sites/all/themes/casa/template.php:26) in /home/kansascasa/public_html/sites/all/themes/casa_m/template.php on line 80

This is the code:

    function casa_views_post_execute(&$view) {
    watchdog('theme', print_r($view->result[0], true));
  if ($view->name == 'programs2' && !empty($view->result)) {
    //drupal_goto('node/' . $view->result[0]->nid);
  }
}

Second one:

function casa_views_post_execute(&$view) {

}

What is the fix for this? Appreciate your help in advance.

I'm assuming you have two separate themes. Perhaps the theme in the casa_m directory is a subtheme?

If the machine name of the theme in the /case_m/ directory is casa_m , then change the function name to casa_m_views_post_execute(&$view)


What is the "contract" for EventSubscriberInterface functions? The EventSubscriberInterface can be used to listen for events, and getSubscribedEvents is used to announce which events an implementation would like to subscribe to.
The getSubscribedEvents must return an array which holds the type of events an implementation would like to subscribe to, as well as the function which is to be invoked when an event triggers.
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => [
        ['redirectToLoginPage'],
      ]
    ];
  }

The documentation is very sparse on the function :

The method name to call (priority defaults to 0)

By looking at other implementations, I see that the function may return TRUE, FALSE and even implementations of Response. An example implementation could thus look like this :
public function redirectToLoginPage(GetResponseEvent $event) {
  $random = rand(0,2);
  switch($random) {
    case 0:
      return TRUE;
    case 1:
      return FALSE;
    case 2:
     $response = new RedirectResponse('/user/login', 301);
     $event->setResponse($response);
     return TRUE;
  }
}

What is the "contract" for the function which subscribes to events? Specifically, what is the impact of returning TRUE and/or FALSE from this function?

The contract is the event class itself. In case of GetResponseEvent (deprecated by the way and will be replaced by RequestEvent in future Drupal releases) you can set a response, this will stop the propagation of this event and the kernel will return the response as an answer to the request.
From where do you have the example code, I'm not sure what case 0/1 is trying to do? In the Symfony default dispatcher the return value is ignored.