Disable caching on a custom plugin block I read a lot of posts on how to disable caching on a custom block but none seemed to give the perfect solution.

$build['#cache'] = ['max-age' => 0] or public function getCacheMaxAge() { return 0; }: Do not seem to work, or at least for authenticated users
\Drupal::service('page_cache_kill_switch')->trigger(): Kill the complete page cache, not only the block ones
Lazy builders: Seems to work only for anonymous users

In my case, I have a block which renders a random node and it's clearly an issue while I'm not able to refresh this cache.

So how to set up such a block? (Drupal 8.4.3)

Posts giving not working solutions:

How to prevent a block from being cached?
How do I correctly setup caching for my custom block showing content depending on the current node?

Edit:

public function build() {
    [...]
    if ($prev_node) {
      $render_controller = \Drupal::entityTypeManager()
        ->getViewBuilder($prev_node->getEntityTypeId());
      $build = $render_controller->view($prev_node, 'pagination');
      $build['#node']->field_custom = 'something';
    }
    return $build;
}

public function getCacheMaxAge() {
    return 0;
}

Thank's to @Clive, it seems my issue is not linked to the block cache itself, but to the entity I render in this block. If so, I have no ideas how on to resolve this issue.

After many searches, D7 cache_clear_all('field:node:10', 'my_field') function seems to do what I want to do. What is its equivalent for D8 ?

I got the same issue that you, here is what it worked for me.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function MY_MODULE_preprocess_block(&$variables) {
  $blocks_to_cache = [
    'SOME_block',
  ];
  if (in_array($variables['base_plugin_id'], $blocks_to_cache)) {
    $variables['#cache']['max-age'] = 0;
  }

}

So, In my my_module.module I search if I'm displaying this block, then I clean the cache for that block. You can several block names.


Easiest way to add x-webkit-speech to the search block's input element I am creating a zen sub theme and I was wondering what't the quickest way to add the x-webkit-speech attribute to the search box so user's can search with their voice? I know there is a Drupal project that can modify the search for me but I would prefer to do it in my templates somewhere so the rendered output is something like...

<input title="Enter the terms you wish to search for." type="text" x-webkit-speech id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">

use hook_form_alter on the search_form and add an HTML attribute via the #attributes for x-webkit-speech.


Is there a way to trigger an action on a php exception in Drupal 7? Whenever a php error/exception occurs, I'd like to log the error and optionally send an email off to the site admin.  Is there an easy way to do this with Drupal 7?  Maybe an existing module or a combination of existing modules?

I have a long, non-drupal technical background, and I've done this many times over in other frameworks and custom stacks (mostly Python).  Not that all frameworks should be created equal, but I figured I'd ask if there was a module for this before going off and developing my own.

I feel like I should be able to use the standard "recent log messages" for my purposes, but two things would need to be added to it.  First, I would need to log php exceptions.  Second, I would need to have the ability to send these log messages in an email.  Now, I understand that logging php exceptions to the "recent log message" table wouldn't be totally all inclusive since the logging php code itself could have a bug in it.  But if that was my only only limitation, I'll settle for the 95% solution.

Any direction at all will be appreciated.

I'm glad this question was asked some time ago, and Thanks to @coderama for offering a bounty for this. I make questionnaires/challenges to Druplars in my local community, and this was a question there.

PHP allows you to set error and exception handlers. This similar to how you register class autoloaders and shutdown functions.

See set_error_handler

  Sets a user function (error_handler) to handle errors in a script.

  This function can be used for defining your own way of handling errors
  during runtime, for example in applications in which you need to do
  cleanup of data/files when a critical error happens, or when you need
  to trigger an error under certain conditions (using trigger_error()).

Also, you can set an exception handler to handle uncaught exceptions. See set_exception_handler

  Sets the default exception handler if an exception is not caught
  within a try/catch block. Execution will stop after the
  exception_handler is called.

Drupal takes over these two when it initializes the environment. even before bootstrapping advanced bootstrap levels, such as the database, variables, and full bootstraps.

If the error happens in Drupal-handled request, it will be handled by either of these handlers (error or uncaught exception handler) unless it was overriden by other modules (Devel's error handler, and other error handling modules or server-side implementations, possibly New Relic).

Both of these functions call _drupal_log_error() to proceed to the logging behavior in Drupal.

The default error handling (and other logging) functionality is based on the watchdog() function.

watchdog() function invokes hook_watchdog(), which the db_log module implements hook_watchdog to store them in the database. watchdog() function itself is not storing them in the database. Similarly, there is syslog module that can store them in the system log (instead of, or in addition to the database log).

If you want to call your own logging/reporting tool, you can simply create a module and implement hook_watchdog() to log them. Note that watchdog() is called to log events that you probably don't want to log, such as users logging in, node CUD events, user registrations, etc. You can filter them down by inspecting the parameters passed for the hook implementation.


Rename nodes based on field Basically, I want the name of a node to be replaced with the value of a certain field. So if I have a field type called field_new_name, I want the title field to be changed to that field's value.

I found this link http://dropbucket.org/node/823 but I don't quite understand what it's doing. Is this what I want?

If so, as I run this script, is there a way to build to keep track of changes? Because some nodes reference others via hrefs so I'd wanna go back and change those references as well.

Had this question once, came along this Generating node title from node fields

In the reactions, there's a little gem in the comments: https://www.drupal.org/project/auto_entitylabel
You can use Tokens and al kind of this stuff ;-). When your field is field_foobar then you'll have the tokens [field_foobar-formatted] and
[field_foobar-raw]


How do I modify a node's body (or any field) on display as `hook_node_view`? So I am trying to upgrade my modules from Drupal 7 to 8 and some things have been pretty straightforward so far, but I'm stuck at a particular function that I just can't figure out how to implement on Drupal 8. Figuring out exactly how to make these changes on 7 was difficult enough, involving a lot of playing around with print_r. Maybe my approach last time was not the right way and therefore I'm already on the wrong track for Drupal 8. Anyway, I was trying to do a find and replace on node body text to change a pattern into a node URL. The code is below:

 function textreplace_node_view($node, $view_mode, $langcode){
   if($node->type == "article"){
     if(empty($node->content['body'])) return $node;
     $text = $node->content['body'][0]['#markup'];
     $offset = 0;
     $m = array();
     while ( preg_match('/\{\{nodeurl-([0-9]+)\}\}/', $text, $m, PREG_OFFSET_CAPTURE, $offset) ) {
       $offset = $m[0][1] + strlen($m[0][0]);
       $nod = (explode("-", str_replace("{{","",str_replace("}}","",$m[0][0]))));
       $nod = $nod[1];
       $thenode = node_load($nod);
       $text = str_replace($m[0][0], l($thenode->title, 'node/' . $nod), $text);
     }
     $node->content['body'][0]['#markup'] = $text;
     return $node;
   }
 }

I tried looking at how it was implemented in the Book module and the parameters started giving me errors when I changed them to what I saw in the Book module:

function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {

I was getting an error along the lines of $node must be of type EntityInterface...

Any help?

This should work, you are changing $build, which you don't need to return:

function textreplace_node_view(&$build, $node, $display, $view_mode) {
  // your code for $text
  $build['body'][0]['#text'] = $text;
}


css errors main menu I have  this error with my css, what drush commands I can use to fix this? is it a permissions fix?
please guide me step by step

You provide very little information ... Which version of Drupal? (It's Drupal 7 based on the paths.) Which theme have you just enabled causing this problem? It worked before you switched theme, right?

My best guess: You have installed a theme that is a subtheme of Bootstrap without installing the Bootstrap theme itself.


Update the block through ajax I have added a block which shows the no of items added to an entity. I want to refresh the block through ajax as the items are added to an entity through ajax form so whenever I add an item, it will refresh or re-render the block content too.

I found some of the modules, but they are in Drupal 7 and not available for D8 so I want to make it done with my custom module but didn't find anything useful.

UPDATED

I have added the class attribute with the block and whenever I add any items, I made an ajax request through javascript which calls the respective controller and at the same time, I run this too--

// This is a part of the controller function from where I am calling below defined methods.
$this->updateBlock();

protected function getBlock() {
    $block = $this->blockManager->createInstance('block_id', []);
    return $block;
}

public function updateBlock() {
    $block = $this->getBlock();
    $this->response->addCommand(new ReplaceCommand('.block--class', $block->build()));
    return $this->response;

}

But It is not updating the block.

Important part you left out is what kind of ajax, is it a form you are submitting or custom javascript which uses ajax to target a controller endpoint? As this is how we return the code of the block.

But the code you are looking for re-rendering a block is:

$id = '' // the number of the block_id
$block = \Drupal\block_content\Entity\BlockContent::load($id);
$render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
return $render;


common.inc error in newly downloaded Drupal 7.69 I just downloaded drupal 7.69 and tried to configure it.  It gives me a page full of the same error:

  Notice: Trying to access array offset on value of type int in element_children() (line 6656 of /Applications/MAMP/htdocs/KSnew/includes/common.inc).

Here's the relevant part of the code in common.inc, with line numbers:

6648 function element_children(&$elements, $sort = FALSE) {
6649   // Do not attempt to sort elements which have already been sorted.
6650   $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
6651
6652   // Filter out properties from the element, leaving only children.
6653   $children = array();
6654   $sortable = FALSE;
6655   foreach ($elements as $key => $value) {
6656     if ($key === '' || $key[0] !== '#') {
6657       $children[$key] = $value;
6658       if (is_array($value) && isset($value['#weight'])) {
6659         $sortable = TRUE;
6660       }
6661     }
6662   }

Is this a Drupal error??

I think it is PHP related.  According to the Drupal 7 php requirements PHP 7.4 is not fully supported.  If you are running on 7.4 perhaps try downgrading it to 7.3 and see if it makes a difference.

This is probably the relevant issue that you encountered.  Alternatively see if you can use the latest patch in there and post your findings so you can help move the issue forward.


Use $_POST after submit form I create a form and a page with controller in Drupal 8.

I want print value of my example input after submit form.

For example my input name is "Tel_number".

My code in controller page is:

<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
class MymoduleController extends ControllerBase {
    public function mymodule() {
      $form['test'] = array (
         '#markup' => \Drupal::request()->request->get('Tel_number'),
      );
    return $form;
    }
}
?>

But no resault print.

Your controller is in a new request. If you stored the data in the database retrieve it from there. If you did not store the data in submit in some place it is no longer available. You could use a session variable or a url query parameter to transfer the data from the form submit to the controller:

public function myFormSubmit($form, FormStateInterface $form_state) {
  ...
  $form_state->setRedirect('route_to_controller', [], ['query' => [
    'Tel_number' => '123456789',
  ]]);
}

and the controller

public function showNumber(Request $request) {

  $build['test'] = ['#markup' => $request->query->get('Tel_number')];

  return $build;
}


Geolocation open InfoWindow on load I can't get my head around the following. I'm using the Geolocation module to show a map on my website and I want the InfoWindow to be open by default.
I found that this should be possible by using the following code:
infoWindow.open(map,marker);
Or as the geolocation module does: infoWindow.open(that.googleMap);
But because I don't create the markers and infoWindows I don't know what there name is. I tried figuring it out by looking at the code of the Geolocation module by can't seem to find it out. How do I loop passed all markers en infoWindows to open them when the map is fully loaded?

I did some more digging around in the module and decided to not build to loop but just use the one existing in the module. So I created a patch for Geolocation modules adding this line
currentInfoWindow.open(map.googleMap, currentMarker);

To line 83 of the geolocation-marker-infowindow.js file.


Node relations (one content type) Question: I have a content type "VIDEOS" and have added 20 videos - 1 through 20. I want to achieve a functionality like if you are watching video x, the next 3 videos are showing in the sidebar, example -> when you are watching video 2 in a block in the sidebar videos 3, 4, 5 are showing up. When you watch video 7 - in the sidebar videos 8, 9 10 are showing up and so on.
Any ideas? I know it will be done somehow with Views but cannot figure it out.

BR, Ivan Ivanov

I would do that with a little code in a custom module...

For the purposes of this example my module is called misc, but replace everywhere is says misc with the name of your your module.

First create a block:

function misc_block_info() {
    $blocks['next_four'] = array(
        'info' => t('Show the next 4'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $blocks;
}

And then define where it's content comes from:

function misc_block_view($delta = '') {
    switch ($delta) {
        case 'next_four':
            $block['subject'] = '';
            $block['content'] = next_four();
            break;

    }
    return $block;
}

And then define the content of the block:

function next_four() {
    $output = '';
    if(arg(0)=='node') {
        $node = node_load(arg(1));
        $query = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('n.type', $node->type)
            ->condition('n.status', 1)
            ->condition('n.nid', $node->nid, '>')
            ->range(0, 4)
            ->orderBy('n.nid', 'ASC');
        $nids = $query->execute()->fetchCol();
        $nodes = node_load_multiple($nids);

        $output .= '
';
        foreach($nodes as $node) {
            $output .= '
nid).'">'.$node->title.'
';
        }
        $output .= '
';
    }
    return $output;
}

What this code does is:

Take the nid of the current node
Does a query to get more nodes of the same type with an nid height than the current page.
Loads each node and outputs the node title, with a link to the node.

This will work for any content type. If your HTML is going to be any more complex than this then I would suggest using the hook_theme function to create a template file for your block.


Automatic Validation Using drupal_form_submit I have a content type (call it my_type) with some required fields. One of the fields uses the email module, so if I try and create a my_type node using Drupal's built in node create page and I put 'notanemail' as the email address, the node will not be created and I get an error saying 'notanemail is not a valid email address'.

When I make a node programmatically using drupal_form_submit, it does not do the validation and the node is made even though I put incorrect values in fields.

I don't want to implement hook_validate if I can avoid it. I would rather use the build-in validation. Is this possible?

Field validation is made only against node form submission, so you need to imitate this in your code.

If you are using Drupal 6, try this solution:https://stackoverflow.com/a/6471821/1387163

For Drupal 7 solution can as following:

$node = new StdClass();

$node->type = 'my_type';
node_object_prepare($node);

// assign node field values here ...

$form_state = array (
  'node' => $node,
  'values' => (array)$node,
);
$form = drupal_get_form($node->type. '_node_form', $node);

node_form_validate($form, $form_state);

$errors = form_get_errors();

if ($errors) {
   // ...
} else {
   // ...
}


How do I attach a library to contact forms? Simple question, I just need to know how to attach a library to Drupal 8's contact forms.  I recently made a similar post for attaching a library to a view, that was accomplished by adding {{ attach_library('mytheme/mylib') }} to views-view--myview.html.twig, but doing the same to contact forms is less obvious.  If the preferred way to attach a library is through twig templates can someone please advise me on what the naming convention is for contact-form twig templates?

Enable twig debug in your develop environment, then you can see through HTML comments all theme suggestions, then create a twig file with based in what you want template.

Original post here.

  Debugging Twig templates

  The Twig templating engine offers a debug tool.

  The Drupal 8 implementation also adds an additional tool that allows
  you to locate the template that outputs the markup.

  Enable debugging

  You enable Twig Debugging in sites/default/services.yml. (If services.yml does not yet exist; copy default.services.yml and rename
  it to services.yml.)

  Set the debug variable to true.

parameters:
  twig.config:
    debug: true

Just pay attention, if you not using site's default folder, use that you created.

After turn on debug, clear the cache, then you will see something like this in your HTML

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- FILE NAME SUGGESTIONS:
   x form--feedback.html.twig
   * form.html.twig
-->

If you need create a new name suggestion for a element, use THEME_theme_suggestions_HOOK_alter in your .theme file, and add your suggestion.

Example:

function THEME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'form__' . $variables['element']['#form_id'];
}


Does 'managed file' type form api support the properties #prefix and #sufix? Does managed file type in drupal 7 form api work with #prefix and *#sufix * properties?

$form['myfilefield'] = array(
            '#title' => t('Image'),
            '#type' => 'managed_file',
            '#title_display' => 'invisible',
            '#id'=>'edit-image-example-image-fid',
            '#prefix' => '
',
            '#sufix' => '
',
            '#default_value' => variable_get('myfilefield', ''),
            '#upload_location' => 'public://myimages/',
);

Yea..all though drupal 7 form api for managed_file shows #prefix/#suffix is supported, it did not work for me either.
So I tried using #field_prefix and #field_suffix and it worked. :)
I know this is a old post but I am posting answer hoping it will help someone. :->


Filter node link in the menu by term tid I created one vocabulary is "Mercedes" and create some term for the vocabulary:

- C-Class
- A-Class
- E-Class

I created a menu and create the links no path:

- Front
- Specifications
- Furniture
- Exterior

Then I create one content type "new car" and added one term reference data fields used "Mercedes" vocabulary and configuration allows attaching links to the menu above when creating new node.
Now I want when I visit a node of a term does the menu will only show articles of taxonomy term. Other articles which are mounted on the menu will not show up.

It's a bit unclear what you want to do exactly. Hope this is an answer to your question.

You will have to work with views. Attach the car terms to your articles or vice versa.Then add the term id as a contextual filter. You will be able to output a list with articles specific to your cars or cars that have a specific article.


Export blocks with features extra I installed the Features extra module to export custom made blocks in my Drupal 7 environment. But for some reason, it doesn't work...

What I do is the following:

I create a custom block
I give it a machine name, description, title and body, just like it's required.
I go to Structure - features - Create feature
I create my feature by clicking the custom block under FE Block
The fe_block dependencies fills in automatically.
I download the feature and place it in /sites/all/modules/features
In my install profile I add this line: dependencies[] = custom_blocks
I try to reinstall the website and... nothing!

The blocks aren't showing up in my Block-page, but the feature is... What am I doing wrong in this process? Do I need to enable something or install an extra module in order to get my custom blocks exported?

Alternative:

Use the Panels module to get the ability to create "Mini-panels" which function as equivalents to the standard Drupal block.

I believe there is much better support for exporting mini-panels into Features, since exportability was a key design component for the Panels module.

Personally, I've been successful using Panels, mini-panels, and Features.


Clean URLs disabled even though module-rewrite is on I have a manually installed LAMP environment on Ubuntu 15.10 Desktop and when I came to install Drupal 8 on it i've seen that clean URLs are disabled, so I turned on the Apache2 (2.4.12) rewrite module in the terminal via:

sudo a2enmod rewrite

Than I got:

Module rewrite already enabled

And yet when I cleared the browsers' cache and refreshed the installation page I still get:

  Clean URLs Disabled.

  Your server is capable of using clean URLs, but it is not enabled. Using clean URLs gives an improved user experience and is recommended.

So, if I turned on the rewrite module, why Drupal 8 still can't use them?

I was having the same problem, I opened the /etc/apache2/apache2.conf file and located this portion of the file

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

And found that AllowOverride is set to None. Go ahead and replace it with All.

Restart your apache service when done.


Is there a Drush command to check the distribution version? Just that, Is there a Drush command to check the distribution version?

Let's say I have installed the commerce_kickstart distributionn, how do I check the version of this distribution with Drush?

this one doesn't work:

  drush pmi commerce_kickstart

As far as I know, no.

Since commerce_kickstart is not a module, but a profile, the drush commands for getting info about a module (e.g.):

drush pm-info commerce_kickstart
drush pm-list | grep commerce_kickstart

will not work.


Custom field: users organized into departments I'm building an intranet corporate site, and need to have users linked to departments. The easy way I see this to be done is to create a taxonomy vocabulary with list of departments, and then add custom field to user entity, linking it with corresponding department from departments vocabulary.

Now I want to add a "Person responsible" field to a custom content type (let's name it "Document"), which should be a list of users, organized by departments.

In future a need to use this field to control access to the document may arise.

So, the questions are:

Is my method to link users to departments good enough, or are there better ways? (as this is now in development, I can change everything painlessly).
What is the best way to make "Person responsible" field (a list of users, organized by departments).
Does all this play well with possible future access control needs?

Add a "grouping" to the table settings if you want to group by department etc.

(You would probably want to hide the department field in this case.)

Using taxonomy for user->department relationship sounds fine, and use Views to make all your lists of users/departments (group by):

Make a Vocabulary "Departments" and add some terms to it

Make a Person content type
Add a field to Person which is a taxonomy reference to the Department vocabulary

Download and enable the entityreference module
Modify the fields of the Vocabulary to add a field, which is an entity-reference to a Person node
Call it Person Responsible

Create some content to test with: Create some People, attach them to Departments, then edit the Departments (terms) to assign people responsible
Download and enable the Views module
Create a View of content, of type person. Add title+department fields
Add a relationship to the view "Content: Department"
Add the Person Responsible field to the view, using the relationship you just added

From discussion in IRC, I misunderstood the requirement around Document. It's simpler than described above. Just do:

Create Department vocabulary; add some terms
Create Person content type; add a taxonomy field referencing the Department vocabulary
Create the Document content type; add an entity reference field referencing nodes of type Person
Use Views to display, including "looking through" the entity reference


Show views page based on path I have 3 node types:

category
subcategory
product

These are all linked using Entity Reference module. All pages have a path (using autopath). What I want to do is show a view depending on the path.

So if I go to categories/category-a/ I want to show all subcategories of that category
Same for the products. I want to show all products referenced based on the path.

I'm trying to make a view with path = categories/%

I set a "contextual-filter: content: nid" - "provide default value" - "raw value from url". But when I visit "categories/category-a/" I see the node with this path. The view isn't shown.

Any idea what's wrong here?

You could try out this Article..

The contextual filter should be "content:nid"

The options should be set as follows...

The Relationship should be your "Entity Reference: Referenced Entity" relationship
Under "When the filter value is NOT available" check "provide default value" and select "Content ID from URL"
Apply changes and save view.


Images can not be changed This seems strange to me, but everything worked fine before i made my site live. I set up all the content and made a backup. Uploaded everything to its server but now i can't change my images. When i remove the current image this comes up (see image) instead of being able to upload a new image

And console throws this error:

I have tried all the versions of jquery and my jquery_update in contrib is 7.x-2.7

Could it be something with the permissions? i have site/default/files-775

if you installed any module that alters with the drupal paths or jquery_update module version can cause the issue.


Drupal 7, Default value php snippet missing? Im using drupal 7 and created a content type abc. In abc there is a CCK field called seller. When a logged in user create a new item for content type abc, the value of the seller field would be the name of the person who is logged in. So what I want is a default value for the sellers fiels or you can say that a small piece of php code. But I am not able to find the place for the php code to enter in drupal 7. In drupal 6 there is text area for the php code to enter. But how can this be done with the drupal 7. Any ideas?

This functionality is not part of the Field UI in Drupal 7.  You'll need to install the CCK module.


How to get the URL of the entity reference node? I'm building a site of course video，one course includes many video clips. I have created 2 content types, one is for the Course ,and the other is for the Video.

In the course content type, I set a field of entity reference to make a relation between course and video.

And then I create a view to display the video list on the video node page, it works. I wonder how can I add the link of the relative course node page on this video node page, how can I get the URL of the entity referenced course node page?

Any help would be great! Thanks in advance.

This is a very late answer, but hopefully it will help others looking to get the raw URLs for related content (especially if you're building a custom theme file for the view).

In the view:

Under "Relationships", add a Entity Reference: Referenced Entity relationship for the related field.
Under "Fields", add a Content: Path field
Set that field to use the relationship.
In the field settings, deselect label; under style settings, set the wrapper HTML to none.
Under "Rewrite Results", select "Rewrite the output of this field"
Use the replacement patterns to add just the [path] token. If you already have a separate Path field selected in the view, it may show up as [path_1] or a similar name.
Save & test the view.


How to get list of all keys defined in the routing e.g path, defaults, options etc and how can we add new custom key? route_with_two_nodes:
  path: '/foo/{node1}/{node2}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::foo'
  options:
    parameters:
      node1:
        type: entity:node
      node2:
        type: entity:node

I need to get list of all keys path, defaults, options etc, where is it defined in Drupal Core ? so that if I need to add custom key and extend it

Add a route enhancer:

Example how _form gets replaced by _controller:

Drupal\Core\Routing\Enhancer\FormRouteEnhancer:

<?php

namespace Drupal\Core\Routing\Enhancer;

use Drupal\Core\Routing\EnhancerInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;

/**
 * Enhancer to add a wrapping controller for _form routes.
 */
class FormRouteEnhancer implements EnhancerInterface {

  /**
   * Returns whether the enhancer runs on the current route.
   *
   * @param \Drupal\Core\Routing\Enhancer\Route $route
   *   The current route.
   *
   * @return bool
   */
  protected function applies(Route $route) {
    return $route->hasDefault('_form') && !$route->hasDefault('_controller');
  }

  /**
   * {@inheritdoc}
   */
  public function enhance(array $defaults, Request $request) {
    $route = $defaults[RouteObjectInterface::ROUTE_OBJECT];
    if (!$this->applies($route)) {
      return $defaults;
    }

    $defaults['_controller'] = 'controller.form:getContentResult';
    return $defaults;
  }

}


Allowing a user to edit ONE view I have a staff member that needs to be able to update a View in the drupal admin area...specifically they need to be able to change the node id displaying in a block.

Is there a way to allow this person to edit just this view?

And if that's not possible what permission do I need to give them?

Thanks!

I don't know that that's possible as described, but you could do something like this:

create a content type with only one field, accessible to the staff member
add an entity reference to the content type housed in the view

  Provides a field type that can reference arbitrary entities

create a relationship to the staff member content type

This would allow the Staff member to change the value in the content to which they have access, which would affect the View, but not directly have admin access to the View or the Admin sections of the Views UI


Setting a Twig to a specific Form Container As the title says,

There is a specific Form Container that I would like to add a twig to that is on a page having its own twig. No theme hook name suggestion is provided when I inspect its element.

My purpose is to style the specific form to be a credit card form.

You could try to add your own template suggestion via hook_theme_suggestions_HOOK_alter, which would mean hook_theme_suggestions_container_alter. There you might target the container by id or some other attribute (id does not seem promising here).

The container.html.twig does only provide a wrapping div around other content. While you could add more html to this, you might have to think about if container.html.twig is the right place to start here.


How to get field values of a just created (or not yet) node? I am calling node_load() function in a custom module and it returns only part of the variables like title, uid, vid, status (all the meta), but it never returns actual field contents. I tried node_page_view(), tried menu_get_object() - all in vain, no field values.

What am I doing wrong? Is this because maybe my module is calling node_load() too early before the saving node, but then how it has already $node->title, $node->nid and other values? If they are some kind of prepared values, then how can I get the same prepared value for a custom field?

And here is the code from the Community documentation page Sending Notification Messages that I am using in my module:

/*
 * Implements hook_node_insert().
 */
function foo_node_insert($node) {

  $message = message_create('foo_message_type', array('uid' => $node->uid));

  $wrapper = entity_metadata_wrapper('message', $message);
  $wrapper->field_node_ref->set($node);

  $options = array(
     'rendered fields' => array(
       'message_notify_email_subject' => 'field_rendered_subject',
       'message_notify_email_body' => 'field_rendered_body',
     ),
  );

  message_notify_send_message($message, $options);
}

and it works just fine for the message subject, however for some reason I can't get node body to be mailed properly.

I tried to see the content of the $node variable in the following code from example module:

elseif (isset($message['params']['message_entity']->field_node_ref)) {
    // This is a node.
    $nid = $message['params']['message_entity']->field_node_ref[LANGUAGE_NONE][0]['target_id'];
    $node = node_load($nid);
    $messageid_params['uid'] = $node->uid;
    $messageid_params['nid'] = $node->nid;
    $messageid_params['cid'] = 0;
    $messageid_params['time'] = $node->created;
    if (variable_get('mailcomment_alter_subjects', 1)) {
      $subject = $message['subject'];
      $subject = variable_get('site_name', '') ? '[' . variable_get('site_name', '') . '] ' . $node->title : $subject;
      $message['subject'] = $subject;
    }
    dpm($node);
   }

and unfortunately my custom node field always returns empty:

field_description (Array, 0 elements)
$...->field_description

All that I needed to do was using

$node = node_load($nid, null, true);

instead of just

$node = node_load($nid);

and now the node is loading as expected.


How to create an rss.xml feed on my Drupal 7 site? I would like to set up an RSS feed on a new site, but having never done this before I am unsure of where to start.

I've got an rss icon on my page and I would like to create a http://demo.drupalizing.com/corporateclean/rss.xml equivalent which is available on this demo site:

http://demo.drupalizing.com/?theme=corporateclean

How do I do this?

You said you're using the views module, so yes -- very doable:

Go to admin/structure/views/add.
Give the view a name (required), add any (basic) additional configuration options you might want, and then under Create a page, select Include an RSS feed.
Give the RSS feed a path (you'll see the box).
Continue & edit, configure the view like normal, then save.


University hierarchy in drupal 7 I'm completely new to Drupal. I've been reading a lot of questions but I could not find anything that fits my needs. I need to create an internal site for my university.

There is one person that is the university coordinator (UC). This person should be able to add a department coordinator (DC) in a way that there are two fields in the form: department name (text field) and the email of DC. After submitting the form a new user should be created with the username the same as name in the email (before @) with a random password that is sent to the email address. This user should be below UC in the hierarchy. DC then should be able to add institute coordinators (IC) the same way. Each DC should be able to manage their ICs. How can I set-up this scenario? Which modules should I install? Is it possible without writing code?

We need university coordinator role, we can create it in People > Permissions > Roles.
Next, we create department coordinator. We do it just like in first step.
University coordinator can make a new user and set a role to it. So we create user DC, set the e-mail dc@example.com and set the password loremipsum. Standalone Drupal has not possibility to generate a random password.

Then, to let department coordinator manage the insitute coordinators you should install Administer Users by Role. One problem - this module don't let you to manage content created by the users.


Assign User Permissions to a File? My scenario is as follows:

I'd like to create 2 node types "public file" and "private file".  Each node type has the file field for file uploads.  I would like the ability to assign user permissions to any file that is uploaded to the private node type.  The users would be managed through the Drupal User module.

Thanks in advance!

The closest out-of-the-box option is to use a combination of the public (public://) and private (private://) file system.  Public files can be access by anyone with a url to the file. They're served directly from the server without really having to deal with drupal.  Private files on the other hand require the user to log in.

The downside to the private file system is the files are basically streamed to the end user via php which is slower. There are ways around this but if you're not expecting heavy download traffic then I wouldn't worry about it just yet.

The way access control is handled is via the node.  You can create a single filefield and attach it to a any content type.  Let's just say we're using the 'article' content type for now with a single filefield that supports both public and private storage.  When you add a file to the article you can choose the private file system.  You can then use any of the node access control modules (tac_lite, og, etc.) to control who can see the node.  Those that can see the node can then download the file.


how do chmod a directory in drupal I want to enable pictures for users in drupal http://drupal.org/node/22271
and I am not sure how to chmod the directory so that users can save their pictures in it.

Thank you for your help in advance.

You want to go through this guide.  It discusses in depth the appropriate filesystem permission settings you should have on every part of the Drupal installation (public files, private files, etc.)  If you follow that guide to the letter your filesystem problems will sort itself out, and you'll have a more secure Drupal installation.  Let me know if you have any questions.


Calling hook_entity_view from a theme Is there any way to call hook_entity_view() from a theme?

I tried adding the implementation to the template.php file, but the function is not called.

I know I can do it via custom module, but as it's a rather UI addition, it would make more sense to do through theme.

Thanks!

hook_entity_view() will only be invoked for modules so no chance of putting it in a theme unless you want to change how something works under the hood.

It's not a problem though, as all alter hooks are invoked for themes; so you can use hook_entity_view_alter() instead.

  This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete entity content structure has been built.


How to import beans using the migrate module? The migrate module allows you to migrate many different kinds of content with what it calls Destination Classes. However i don't see support for beans in there.

I've searched in https://drupal.org/project/migrate_extras and https://drupal.org/project/issues/migrate_extras?categories=All to no avail. So my question is how would i go about importing beans into my DB?

For the moment i've been using bean_create, however I believe an implementation that hooks into migrate would be better.

The default Destination Classes are https://drupal.org/node/1006988

This forum post shows an example DestinationHandler and Migration

https://drupal.org/node/2141211


Form added to content in hook_page_build lacks of AJAX I'm adding a form to the footer using hook_page_build because a want to show it using a popup, so when user launches the popup the form appears inmediatly.

The problem is that the form is not AJAX processed: the submit button hasn't the ajax-processed class so AJAX is not working. But if I render the form using hook_menu and drupal_get_form the form has the ajax-processed class and AJAX is working.

Form code fragment:

  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Your Personal Message'),
    '#default_value' => '',
    '#cols' => 50,
    '#rows' => 5,
    '#description' => '',
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send Message'),
    '#ajax' => array(
      'wrapper' => 'myform-wrp',
      'callback' => 'myform_ajax_callback',
    ),
  );

Implementation of hook page build:

function mymodule_page_build(&$page) {

  // Get the current $node
  [...]

  $form = drupal_get_form('mymodule_form', $node);

  $page['footer']['my_form'] = $form;

}

Hook menu that the retrieves a working AJAX form:

function mymodule_menu() {

  $items = array();

  $items['node/%node/mymodule-form'] = array(
    'title' => 'My form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form', 1),
    'access callback' => TRUE,
  );

  return $items;
}

I've tested it with hook_page_alter too.

What can be needed to ajaxify this form? I suppose is something related to adding the form too late...

The problem is the element's name: submit. In the rendered page there's another form that have the same button name (submit), so the AJAX layer just ofund one of the buttons but not the two.

To fix this just rename the element's name:

 $form['myform-submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send Message'),
    '#ajax' => array(
      'wrapper' => 'myform-wrp',
      'callback' => 'myform_ajax_callback',
    ),
  );


Add to cart form AJAX not working when loading a product display via AJAX I am trying to create "quick buy" functionality. I have a product listing and a customer is able to click on "quick buy" for that product and then I want to be able to load up a view mode for that product display in an overlay which has a few product display fields including the add to cart field.

I can get the loading of the product display via jQuery load (or ajax) no problem, the issue is that the add to cart button is not working via ajax and the customer is instead redirected to the callback (which is now the action in the add to cart form).

Javascript code to load product display node:

$('.quick-buy:not(.ajax-processed)').addClass('ajax-processed').click(function(e) {
  e.preventDefault();
  $.ajax({
    url: '/product/get/ajax/'+$(this).attr('rel')
  }).done(function(result){
    $('#quick-buy').html(result);
    Drupal.attachBehaviors();
  });
});

Module code:

function tweaks_menu() {
  $item['product/get/ajax/%'] = array(
    'page callback' => 'tweaks_get_product_ajax',
    'page arguments' => array(3),
    'access arguments' => array('access content'),
  );
  return $items;
}

function tweaks_get_product_ajax($nid) {
  $node = node_load($nid, NULL, false);
  $node_view = node_view($node, 'product_quick_buy');
  $html = drupal_render($node_view);
  print $html;
}

I have also tried:

function tweaks_get_product_ajax($nid) {
  $node = node_load($nid, NULL, false);
  $node_view = node_view($node, 'product_quick_buy');
  $html = drupal_render($node_view);

  $settings = FALSE;
  $javascript = drupal_add_js(NULL, NULL);

  if (isset($javascript['settings'])) {
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
    $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $javascript['settings']['data']));
    $settings .= ');
  }

  print $html . $settings;
}

...to no avail.

The reason why it redirects after adding to cart is because the add to cart form doesn't use ajax by default. Wich causes it to redirect the user when submitted.
If you want it to use ajax you'll have to alter the submit button via a
HOOK_form_FORM_ID_alter.

For more info on the form ajax functionality
FAPI ajax

However by doing so you'll alter all the add to cart button forms on your entire website to use ajax.

So a better solution might be to create a custom add to cart form just for the product_quick_buy view-mode and display that instead of the standard form. This form can then use ajax to call it's submit handler.

Also I think your ajax link implementation for the hook_menu doesn't follow the coding standards.

function tweaks_menu() {
  $item['product/get/ajax/%'] = array(
    // -- your code --
    'delivery callback' => 'ajax_deliver', // Tells drupal we'll be returning an ajax renderable array
  );
  return $items;
}

function tweaks_get_product_ajax($nid) {
  $node = node_load($nid, NULL, false);
  $node_view = node_view($node, 'product_quick_buy');
  $html = drupal_render($node_view);
  // Instead of printing we're generating an ajax renderable array and return that
  $commands[] = ajax_command_html('YOUR_JQUERY_SELECTOR_HERE', $html);
  return array('#type' => 'ajax', '#commands' => $commands);
}

More info about ajax links Tutorial on ajax links


How to change the content moderation state in a custom submit handler? I am trying to change the content moderation state from draft to submitted programatically.  The Content Moderation module adds a field to content types with a dropdown to change the state, but I want to hide this field from users and instead show a custom submit handler that changes the form state.

I can change the default value of the moderation field with code like this:

  $form['moderation_state']['widget'][0]['state']['#default_value'] = "submitted";

But, how do I change the value for the content moderation field using $form_state in the submit handler?

  $form_state->setValue('moderation_state', 'submitted');`

does not work like it does for fields.

Here is the debug output for kint($form['moderation_state']['widget'][0]):

To change the moderation state you need first to get the entity:

$entity = $form_state->getFormObject()->getEntity();

and then change the state:

$entity->set('moderation_state', 'submitted');

and save:

$entity->save();

All the code:

/**
 * Submit callback to submit for approval
 */
function draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  // Getting the entity.
  $entity = $form_state->getFormObject()->getEntity();
  // Changing the moderation state.
  $entity->set('moderation_state', 'submitted');
  // Saving the entity.
  $entity->save();
}


Mixing attributes and line item fields in Drupal Commerce Add To Cart form I am currently working on a Drupal Commerce site that offers highly customizable products with multiple attributes.  I am at the stage where i am trying to theme my add to cart form, and am a bit lost.

In my theme, I have created a hook_form_alter, and check for my add to cart form.  The $form variable has 2 groups of form fields:

$form['attributes']        // Contains 'Attr_1', and 'Attr_2'.
$form['line_item_fields']  // Contains 'Attr_1_c1', 'Attr_1_c2', 'Attr_2_c1', 'Attr_2_c2'

So each attribute has 2 customization options specific to that attribute.  I would like to output my form like so:

Attribute 1: (Select Box)
    Customization 1: (input)   // Attr_1_c1
    Customization 2: (input)   // Attr_1_c2

Attribute 2: (Select Box)
    Customization 1: (input)   // Attr_2_c1
    Customization 2: (input)   // Attr_2_c2

Thus grouping the proper customization line_item_fields with the proper attributes.  However, since attributes are already grouped in the $form variable, and are separate from the line_item_fields, I am not sure how to do this.  Any thoughts on the best way to proceed?

You may find it easier to organize the form elements in a form template.

e.g

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state{
  $form['#theme'] = array('commerce_add_to_cart_form');
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path){
  return array(
    'commerce_add_to_cart_form' => array(
      'render element' => 'form',
      'template' => 'form--commerce_add_to_cart',
      'path' => $path . '/templates',
    ),
  );
}

Then you can use a file in

MYTHEME/templates/form--commerce_add_to_cart.tpl.php

and in the template file

print drupal_render($form['element_name']);
// or
print drupal_render_children($form['element_name']);

to specify exactly where to render each form element.


How does POST action work on a drupal login form? I was looking at the login form tag of Drupal and was surprised that it does not reference any specific page to handle login. Example:

<form action="/node?destination=node" .....>

Or if I go to the login page directly:

<form action="/user/login" .....>

or

<form action="/user" .....>

So how does this work? How does the browser know which page to submit the POST data to?

Drupal uses the Form API to handle this. It doesn't need a specific page to handle the POST data because of the way its structured. Also see user_login to get an idea of how it's implemented. You can see that it sets specific validation functions to be called when the form is submitted, and then it moves on to user_login_submit (this part happens due to the default naming conventions of the Form API). There's other magic in there that makes this all work, but it usually isn't necessary to understand it in order to develop with Drupal.


Node edit form with embedded form not executing custom submit handler I'm porting a module that currently works with Blocks/BlockForms to Paragraphs/NodeForms. I'm inserting an embedded form inside a Paragraph inside a Node Edit page using a
hook_field_widget_entity_reference_paragraphs_form_alter. The general structure where the form gets inserted is:
$form['field']['widget'][0]['settings'][form here]

After this the form displays as expected on the node edit page.
The inserted form goes through a number of #process steps. The element in question is a select form that when the button underneath it is pressed, is supposed to retrieve some data via a custom submit handler and place it on the page with ajax:

The array for this element looks like this:

You can see the custom submit handler that is supposed to fire when 'Select Segment Set' is pressed
After debugging, I've found that the entire NodeForm appears to be submitted to the backend, and the only handler that is found is from some other field that uses ajax. In short 'updateSegmentSet' is never discovered as a submit handler. When I debug the original module based on block/blockforms, I do see the correct submit handler being discovered. Now in the latter case, of course a blockForm is submitted to the back end with the correct plugin. Given that this is basically a form within a form within a form, is there something special I have to do to get the custom submit handler to run? I've read a few things online e.g. the 'settings' key and '#tree' = true.
EDIT
The Ajax property looks like this:
      '#ajax' => [
        'callback' => [$this, 'updateSegmentSetAjax'],
        'wrapper' => $wrapper_id,
      ],

  public function updateSegmentSetAjax(array &$form, FormStateInterface $form_state) {
    $button = $form_state->getTriggeringElement();
    // Go one level up in the form, to the widgets container.
    return NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -2));
  }

As best I can tell, this is never called either.

I came across https://www.drupal.org/forum/support/module-development-and-code-questions/2015-09-03/put-a-custom-form-inside-node-form which, while old, claims that what I wanted to do is not possible. To get this to function the way I wanted I:

Attached a JS event handler to the embedded form submit buttons that performed .preventDefault()
This handler then .ajax'd a custom route that I created.
In the Controller for that route, I had to perform all the primary operations for submitting the form and return markup back to the .ajax call.


Entity reference get all related items in a view I'd like to have a view block on my content page that shows ALL related content. ALL in the sense of chaining - if Node A references Node B which references Node C which references Node D, then nodes B, C, and D all show up on Node A's page even though it itself is only related to Node B. How can I set this up?

One way of doing this in a non-programmatic way is to use views_field_view. With this method you will only get a set number of nesting levels - for example 4 levels: create a view of your specific node Content Type with 4 Pages, A, B, C, and D. In Page A, insert a Views Field that references Page B, in B a field to Page C, and in C a reference to page D. Pages B, C and D should have a contextual filter for a Node ID (nid). In each page, the Views Field View field should pass the Node Reference as an argument to the next Page. I hope this is clear. Let me know if it's not, and I can expand this.

EDIT: If you are looking for "infinite depth" I suggest that you look at the programmatic alternative for Views, EntityFieldQuery(). Perhaps a recursive call to a function that does the query, while you build a global multi-depth array with the data you need, then theme it as a table.


hook_node_view selectively responding I have inherited a complex site with multiple node type.

My current task is to prevent some nodes from loading based on some preset conditions. To accomplish that I used hook_node_view in the following function:

function accessibility_node_view($node, $view_mode, $langcode){
    drupal_set_message('Node View Responding');
}

That's just a simple test but I find that code responds on some nodes types but not on others.

Does anyone know a reason why that would be happening, please?

After a long and confusing time experimenting with a lot of various hooks, I finally found hook_node_access.

I'm not sure if I had tried it previously but it seems to do the trick.

I used the following code to test when any node of any type is being viewed at which point I test for the presence of an particular taxonomy and value to determine if I want certain roles to view and read the page:

function mymodule_node_access($node, $op, $account){
    if($op == 'view'){
        if( isset($node->field_accessibility['und'][0]) ){
            ....
        }
    }
}

I hope that helps @longboardnode


Caching Views: Query results Vs Rendered Output Can you think of an example when it would be beneficial to have the Query Results cache time be longer than the Rendered Output time? or vice versa?

First some explanations:

Caching your query results, means you store the results. So the next page load you don't have to perform your heavy time consuming SQL query again.

Caching the rendered output means you cache the generated HTML output; the system does not have to render the page again.

It would make sense to have most of these exipire at the same time,  after all, if the data changes, you'd want to show the changes to the user.

The only situation I can think of to cache the query results longer than the SQL data, is in a situation where the template file changes very often. Your theme might for instace randomly change the color of each table row, or show the current time (provided via a theme variable and a preprocess function) on the display. You might want to keep this out of the cache to give the user the impression the data is current, while still being able to serve the page relatively fast.

Caching the rendered output longer than the query seems like a bad idea. You'd be performing the resource intensive SQL query for new data, yet discard the data directly because you choose to display the old data instead. So I'd recommend against doing that.


Uploading image to a node via Angular to Drupal 8 using REST I have figured out how to upload files from Angular to Drupal 8

......
submitCommunity: function(params) {
  var package = {
    "_links":{"type":{"href":"http://dang.dev:8888/rest/type/file/file"}},
    "filename":[{"value":Math.round((Math.random()*1000)).toString() + '.jpg'}],
    "filemime":[{"value":"image/jpeg"}],
    "data":[{"value":params.bannerImage}] //params.bannerImage = B64 encoded string of the image
  };
  $http.post('http://dang.dev:8888/entity/file', package, config).then(function(response) {
    var fileId = response.headers().id; // the file ID of the newly created file entity.
  });
},
......

My question is, what if I have a content type that has an image field in it? Specifically, my content type is of type community and contains a field called field_banner_image. Below is what I have now, however, it produces 422 Unprocessable entity with a response of:

{"error":"Unprocessable Entity: validation failed. field_banner_image: This value should not be null."}

field_banner_image is required hence the error, but I have no idea what field_banner_image expects me to send it.

.....
submitCommunity: function(params) {
  var package = {
    "_links":{"type":{"href":"http://dang.dev:8888/rest/type/file/file"}},
    "filename":[{"value":Math.round((Math.random()*1000)).toString() + '.jpg'}],
    "filemime":[{"value":"image/jpeg"}],
    "data":[{"value":params.bannerImage}] //params.bannerImage = B64 encoded string of the image
  };
  $http.post('http://dang.dev:8888/entity/file', package, config).then(function(response) {
    var fileId = response.headers().id;
    package = {
      _links: {'type':{'href':'http://dang.dev:8888/rest/type/node/community'}},
      type: [{'target_id': 'community'}],
      title: [{'value': params.title}],
      body: [{'value': params.body}],
      field_banner_image:[{'value': fileId}]
    }
    return $http.post('http://dang.dev:8888/entity/node?_format=hal_json', package, config);
  });
},
.....

I've tried field_banner_image:[{'fid': fileId}] and some other combos of key values, but I think I am attacking this wrong. Documentation on this is kind of sparse right now and a lot of it is old D8 beta stuff. Any Ideas?

ImageItem and FileItem are represented as entity references. The ImageItem has the following schema: target_id, alt, title, width, and height.

Only the target_id column is a required property, which can be seen through ImageItem::propertyDefinitions > FileItem::propertyDefinitions >  FieldReferenceItem::propertyDefinitions parent method.

The field should be represented similar to the type property, which also is an entity reference.


Request new password form id I want to know the Request New Password form id. (www.example.com/user/password).

I found out that the register form is "user_register_form" and tried same for password (user_password_form / user_pass_form / user_pass_reset) but nothing worked.

Hope you can help me! Thanks a lot!

Edit: If you could tell me the account form id in the same breathe, the answer would be simply awesome.

Note that print_r will be better in this case because to see the form he desires one must be logged out otherwise you'll get the password reset for the active user, which is different.

Leandros, try putting this in your theme's template.php and visiting user/password (not logged in)

function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_pass':
        print '
';print_r($form); print '
';
      break;
  }
}

It will give you an array of everything that's in there.  Then, say you wanted to change the text "Username or e-mail address" and the text on the submit button you could do this:

function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_pass':
        //print '
';print_r($form); print '
';
        $form['name']['#title'] = 'Please type your username/email quickly.';
        $form['actions']['submit']['#value'] = 'Email it to me!';
      break;
  }
}


Based on user's country filter content of same country? Please find my problem statement here:

  Show all contents of Type "Test" belongings to that country to corresponding user of that country

My Approach:

Created a taxonomy term of country, Mapped this taxonomy in content type "Test" and also Mapped taxonomy to users account setting fields.
Trying to create view that can filter based on logged in user's country(user can belongs to more than one country) to the content's country field.

Trying with Contextual filter, but not figuring out, exactly what i need to give. Please anyone can help me in achieving this?

Or suggest me any other Better Approach

What you're missing is the bridge between users and content, and that comes through Relationships (connecting different tables from the database).

You can do this by approaching from either the content end, or the user end (Content Views or User Views type). Since the goal is to list content, I think it makes more sense to start from the content end, unless you need some more user handling that would be easier from the user then.

Create a Views showing your Content (Page or a Block, which ever suits you best)
Add a Relationship Taxonomy term referenced from field_country (you probably have a different field name), you can require it since you only want nodes in the list that don't have Country empty
Add another Relationship User using field_user_country (you probably have a different field name), it will use the above Relationship by default. You can require it since you need users who also have the Country field not empty.
Add a Contextual filter ID from User Category and it will use the second Relationship by default. Configure it:
When the filter value is NOT available
Provide default value
User ID from logged in user
When the filter value IS available or a default is provided
Specify validation criteria
User ID
Single ID
Hide view
Adjust any other Views settings relevant to you and Save the View
If you've created a Block and need to place it in a Region in your theme, don't forget to adjust the Contextual Views options on the Block configure page.


Ubercart Recurring Payments and Subscriptions:Charge automatically? I'm using Drupal 6 and Ubercart 6.x-2.7.
In my online store I'm going to manage subscription for the products. Every product can be subscribed for some period of time, weekly, biweekly, monthly, semiannually. I'm going to use PayPal PayFlow Pro and PayPal Website Payments Pro gateways to receive payments.

The issue is here how to manage getting recurring payments through this payment gateways? Any php code or something else?

Here I'm including how this process works:

Customer adds required products in his shopping cart.
In the cart there is a select-box per every product for subscription(options: just one time, daily, weekly...)
Customer checks out from the site paying with Credit/Debit card or PayPal account.

Question: How to charge automatically the fee for subscription in the selected period?

You can use this module.

UC Recurring Payments and Subscriptions

Features:

New/improved API for payment gateways to interface with uc_recurring - see hook_recurring_info().
Ability to treat a recurring fee as a new order - so it gets access to everything a new order gets at the time of renewal e.g separate invoices, apply roles etc...
Option for unlimited renewals (ie: renew until canceled).
Option for recurring payments to be set that same as product price (this means that the recurring payments can be based on adjustments of a products from things like attributes).
Conditional action support - sending emails on failed renewals.
Extension API - administrators can configure what will happen on a failed payments, e.g order can be extended and re-attempts as many times as required.

Take a look at discussions here

PayPal community

x.com

Please note module is not stable yet


What are bundles? Can we create custom bundles? Does all nodes have bundles? Also can we create custom  bundles?

Bundles are an implementation of an entity type to which fields can be
  attached. You can consider bundles as subtypes of an entity. With
  content nodes, for example, you can generate subtypes like articles,
  blogs, or products. Not all entity types have bundles, however. For
  example, users do not have separate bundles or subtypes. With bundles,
  you can have as many subtypes as you want. Then, using the Field
  system, you can add additional fields to those bundles such as file
  download field for Articles and location fields for Users.

Read more here and a good article that i found. Hope it helps :-)


How do I display individual date display nodes of a commerce event with recurring dates? I have created a commerce product type for a class that occurs every Monday for 10 weeks. I have the 10 dates displaying in a Calendar view using a start date and a repeat rule. What I can't figure out is how to create display nodes for the individual dates so I can add a recording of the class after it has occurred...possibly required reading beforehand; anyway, is there a way to display individual nodes in this context?

Repeating Dates in Calendar are single nodes that store all the occurances of the event, so for this to work you may have to create single events instead of one that is repeated. Good reading on that issue found here: http://drupal.org/node/298334


Add div after each field of a certain name I'm trying to display a div container after each field item with the name additional_content of my page content type. Right now im trying to preprocess my field but i can't go down to the real field item i want to proprocess...

Is it better to override the template? And how would that work? i have a field called additional_content integrated into my page content type. After this has been printed i want to add a div container to each of this items.

Any help with that?

Copy modules/field/theme/field.tpl.php file into sites/all/themes/YOUR_THEME/templates

Rename it to field--additional_content--YOURCONTENTTYPENAME.tpl.php
(or only field--additional_content.tpl.php if you want to change its template for all content types)

Edit its template like this:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>


Views' taxonomy term page by content type I have two regular content type Article & Blog, both share a term reference field field_tags. When I use Taxonomy term view that come with Views module, it display tags term in both content type.

For example, there are two Article nodes tag as health and three Blog nodes tag as health. Then if I use Taxonomy term view to display health term, it will display five nodes: two Article nodes and three Blog nodes.

Is there a way to separate the display result by content type? For example, if user click on health term on an Article node, Taxonomy term view will only display two Article nodes and if user click on health term on a Blog node, Taxonomy term view will show three Blog nodes.

Prefer not to use an extra module or adding different tag field for Blogs content type. Thank you for helping!

in the view you can filter by your desired content type.

just add the filter criteria named Content: type


Generating a random number without duplicates on blog comment A section of my site is a blog where I allow comments. Each comment has a thumbnail associated with it. If the commenter is a user, then their profile photo is used. If they are anonymous I have a pre-determined photo in place. I want to be able to randomly generate a thumbnail for these anonymous users, but also have no duplicates.

I asked this question here and now have a random thumbnail being generated, but the problem is that there are still duplicates. And it looks like because the comment.tpl.php file is being read on each comment that the random numbers are not being remembered.

How can Drupal remember the number so that it doesn't use it again?

My Code:

$numbers = range(0, 19);
shuffle($numbers);

print "
";
print "";
print "
";

Haven't tested this, but I think this should work. Remove your first two lines of code and place the following in your theme's template.php file (replace MYTHEME with the machine name of your theme):

function MYTHEME_preprocess_comment(&$vars){
    $max = 19;
    $numbers =  $_SESSION['MYTHEME_comment_numbers'] ?: range(0, $max);
    shuffle($numbers);
    $vars['number'] = array_pop($numbers);
    $_SESSION['MYTHEME_comment_numbers'] = count($numbers) ? $numbers : range(0, $max);
}

This makes available a $number variable inside your comment.tpl.php file.

Then, replace your last three lines inside comment.tpl.php with:

print "
";
print "";
print "
";

This will remove already used numbers from your $numbers array until there's none left, and then reset to use the full array again.


How to redirect from node view to node edit page in a view? I need on of the views in my Drupal design, which is using node title linked to the node content view, just redirect form node content view page to that node edit page.

How would it be possible? If it needs coding please write the code. Thanks

(My Drupal version is 7.x)

Steps to achieve:

Add new field: 'nid'

Add nid field to view above the title field.
Exclude nid from display.
Goto arrangement and put it above the title field, so that it can fetch it.

Change to existing field: 'title'

Open title field settings.
Uncheck Link this field to the original piece of content.
Expand REWRITE RESULTS section.
Check Output this field as a link checkbox.
Put node/[nid]/edit to the Link path input.


Pagers of two different contents are conflicting There are two contents in my website, say CA and CB, I created a view for each one and it displays 10 items and for the rest of the items pager is used. CA is in the sidebar first region and CB is the main content which lists some thing. the Use AJAX:Yes configuration is used for CA and Use AJAX:No for CB is used. the problem is when the next link in CB pager is clicked and the page goes to www.example.com/content?pager=2 both CA and CB are going to the second page of the 10 contents. why they are conflicting and how do I can solve this problem?

thanks

You can assign a different PagerID to the pager when editing the View.  This should compensate for the conflict.  By default, all pagers have an ID of 0, but if you need 2 views on the same page, then you need to manually select a different ID for one of them.


Using the back button after logging out shows you pages from the authenticated user's session Using the back button after logging out shows you pages from the authenticated user's session.

I found a solution for this, need to set the header like this to fix this issue-

drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');

But the problem where i need to set this header?
I set the header in index.php file. After that i am not able to see any other pages while i am logged in. (getting page not found error)

Any solution, how to fix this issue??

You can implement hook_init() in any of your custom modules

<?php
/**
* Implements hook_init().
*/
function YOUR_MODULE_NAME_init() {
     drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');
}
?>


Webform does not submit, instead redirects to self My soon-to-be production Drupal site's Webforms have stopped saving submissions; instead it comes back to the same page, complete with the inputted values. I do not have a timeline when it stopped working. In a sandbox environment, Webform 7.x-3.17 works fine.

I'm looking for some suggestions to further debug.

I've tried the following, but to no success:

Disabling any modules that refer to Webform (notably Webform Template and Webform Validation, and my own custom module that had been using hook_form_alter).
Upgrading to the latest Webform (yes I remembered to use update.php).
Based on documentation, combining hook_form_alter($form, &$form_state) with array_unshift($form['#submit'],'my_custom_submit') to insert a custom callback, where I called drupal_build_form($form['form_id']['#value'],$form_state) to emulate a submission.
Obviously flushing caches consistently.
Ensuring that the Webform is published.
Writing a bare-bones module to simply monitor $form_state['executed'] (it always returns false).
Checking my server's error_log both on SSH and FTP.
Checking Reports > Recent log messages.
New: Tried disabling & uninstalling Webform, deleting old Webform files, and installing a fresh new version of Webform; no good.

I'm pretty sure the issue is not isolated to Webform, so it wouldn't make sense to post to their issue queue.

What other debugging methods can I pull out to help crush this bug? If I disable every module without uninstalling, is an entire FTP backup necessary or just SQL?

EDIT: Some more things I've tried as per suggestions (unsuccessfully)

Explicitly defining $cookie_domain and $base_url in settings.php
Looking through Trigger and Action modules for any potential misfiring redirects

I have never had any problem with the Webform module, but if it happened to me I would double check sites/default/setting.php to see if there are any settings for an explicit $base_url or $cookie_domain. The latter is much improbable, since you would probably have problems with logging in.


Change Menu Item's links Dynamically, per page basis I've been looking for this for a while, but found no solution.

What I want is: Whenever someone visits to a user's profile, say http://mysite.com/user/1 there should be an item available in Main Menu, with the link: http://mysite.com/custom_module/1

Here, I'll be dynamically changing the menu item's links based on the current page. How to achieve that?

Thanks.

It depends on how exactly you want to change the links, but views can handle most links if you configure the contextual filters correctly.  Basically, just display a link to the content as the field and then set your filters and contextual filters (getting the argument from the node/user) as you need.

If you just want to change around links for user profiles, there's also the me module.


Creating a Form Uploader? Sorry if this an extremely newby question but I am a beginner and still trying to learn how to navigate through the site.  Anyway, I am trying to create a form uploader.  For example, I want someone to go to their profile page, hit upload, and then a form with 5 or so fields come up where they can fill things out and then upload it to the main content page.

Here is a use case that I am thinking of:  I have a picture that my little sister drew, and I want her to add a description, the title of her picture and date it.  When I hit upload there will be a upload image field and three text fields for the title, date and description.  Then I want it to display on the homepage.

Sorry if that was a really tedious description for a really simple function.  I appreciate all the help though!  Thanks in advance for all your time and help.

Pete

The simplist way is to give your users permission to add a node. This would be done through admin/people/permissions.

To get a node to automatically appear on the front page, the publishing options for the content type need to default to 'Promoted to front page'. Set this up when you are creating your content type.

If you want to create a custom form, the method (perhaps not for newbies) is:

(1) Create a module (.INFO and .MODULE files).

(2) Implement hook_menu (in your new module) to create a url and page where the form is to reside.

(3) Add a function to render the HTML of the form using drupal_get_form.

(4) Add a form builder function and construct your form using an array called $form (see form API for details).

(5) Add a submit button at the end of your form.

(6) To make the form look the way you want it to there are several methods: (i) create a theme function to add to the elements of $form; (ii) use #prefix and #suffix properties to add additional HTML and CSS ids/classes to the rendered form; (iii) manipulate the many ids/classes, rendered by drupal_get_form, with CSS; (iv) use the #markup properties to add additional HTML and CSS ids/classes to the rendered form (not recommended).

(7) Add a validation function, if needed.

(8) Add a submit function using node_save (for nodes) and drupal_write_record (for fields) to insert your form values into the relevant database tables: node, field_data_field_my_field etc.


View Contextual filter for content updated dates I am new to Drupal.

I want to implement a contextual filter in YYYYMMDD or in Unix date format. if I pass a value as 1st Dec 2013 (20131201) then it should return me all the contents who has been updated after that date. I am not able to get how to do it.. I got to know about updated date but its in the format of CCYYMMDD is it same as YYYYMMDD? if not then can I change it to so?

The date format CCYYMMDD is indeed the same YYYYMMDD.

CC means century number as a 2 digit cardinal number where the first century was given the number 00. The present century is century number 20.

YY or YYYY means year (written as a 2 or 4 digit cardinal number with a leading zero if required), The present year is 14 (two digits) or 2014 (four digits).

MM means month as a two digit cardinal number with a leading zero if required.  The present month, January, is written as 01.

DD means day om the month as a two digit cardinal number with a two digit leading zero if required.  Today is day number 24 of January.

In other words, today's date (January 24th 2014) is written 20140124 in both these formats, and December 1st 2013 is written as 20131201 in both these formats.


What are search_index & search_dataset tables for, can I clean them? I am trying to dump sql from local dev site to production server, I found that search_index & search_dataset these two tables are big, made the sql file really big.

I am guessing these two tables are about storing search indexes which I can always to re-index from scratch later. Correct me if wrong.

So is it OK/safe to delete all the records of them?  then export the database, import to my server. By doing this I can reduce the file size of dump file.

Thanks!

These tables are used by the site's search function, as provided by the core's Search module. They're built from your site's content, and the descriptions in code in search_schema() say:

search_dataset - "Stores items that will be searched"
search_index - "Stores the search index, associating words, items and scores"

Though you can ignore/truncate the contents of these tables to keep your database dumps smaller, they will be recreated during cron runs as your site's content is re-indexed. Beware that rebuild times can be a lengthy if your site has a lot of content.

I've always found the Backup and Migrate module to be much handier than command-line MySQL as tables and/or their contents can be ignored, plus do scheduled dumps and  have various export/import profiles.


how to create views with month and day in contextual filter Let suppose I have  actor content type, it has a birthday field (it is date ),
I want get all actor that has equal month and day of birth,I want to create a views with
birthsearch/%/%  path, and then I want pass  month and day to it ,
as exapmle birthsearch/02/25 , it should return all actor that birthday is 25 feb,I think contextual filter is good idea to achieve this but, by default drupal Granularity of date field  is

it is means I can restrict it to year and month, but I cant restrict it to day and month,

my question is how can I have views with month and day in contextual filter (passed to it by page Url)?

I achieve this with below solution,
create birthday field filter in views and set it to something fix =2000-02-02(not important later it will bypass),
then in my custom module  I implement hook_views_query_alter and change condition to what I want  "DATE_FORMAT(field_data_field_birth_date.field_birth_date_value, '%m%d') = :field_data_field_birth_date_field_birth_date_value"; and work correctly,and views page path is sbirthdaymd/% ( as example link will be something like sbirthdaymd/0524 )

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

/**
 * Implementation of hook_views_query_alter
 * @param $view
 * @param $query
 */
function mymodule_views_query_alter(&$view, &$query) {
    if($view->name == 'search_cast_by_birth_and_death') {
//        ym($view->query,'message');
        $url = parse_url(current_path());
        $temp = explode('/', $url['path']);
         if(!intval($temp[1]))
             $temp[1]="0406";
        if($view->current_display=='page_2'){
        $view->query->where[1]['conditions'][2]['field']="DATE_FORMAT(field_data_field_birth_date.field_birth_date_value, '%m%d') = :field_data_field_birth_date_field_birth_date_value";
        $view->query->where[1]['conditions'][2]['value'][':field_data_field_birth_date_field_birth_date_value']=$temp[1];
        }

     }
    }


Generating an absolute node URL from its node id I think the question is self explanatory. I got a node ID and I need to create its absolute URL somehow. I can do this but (I think) this won't work every where in the site:

Node Title

Please correct me if I am wrong.

Is there a function that I can give the node id and returns me back the absolute path of it?

Drupal 8
$nid = 5;
// Or $nid = $node->id();
$node_title = 'Node Title'
// Or $node->getTitle();

Create absolute URL:
// Will output http://example.com/path-to-my-node
$options = ['absolute' => TRUE];
$url_object = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
// In Twig use {{ url_object }}.
// In PHP (outside a render array) use $url_object->toString().

Create absolute link object (and inner span):
// Will output Node Title
$options = ['absolute' => TRUE, 'attributes' => ['class' => 'this-class']];
$node_title = \Drupal\Core\Render\Markup::create('' . $node_title . '');
$link_object = \Drupal\Core\Link::createFromRoute($node_title, 'entity.node.canonical', ['node' => $nid], $options);
// In Twig use {{ link_object }}.
// In PHP (outside a render array) use $link_object->toString().


Changing Drupal theme completely I am a newbie, I am in the middle of the website which was already created using the bartik theme and I want to change the theme completely like the way Main-menu looks and adding the slideshow in the middle of the page. I really don't understand how to do it. Any suggestions? Thanks.

I would recommend starting with the "Stark" Drupal theme.  It's the minimal theme,  easier to customize.

You are also going to need to read about some basic Drupal concepts.  Views, blocks, page templating.

Your question is far too "big" to be answered in this forum.  You will have to read the documentation at drupal.org


Ajaxified form in modal window does not dimiss I have form in modal window with two selects. Second field hidden and appears with ajax after first field selected.

If i click Submit when first select is not defined and second is
hidden - modal window dismisses;
If i click Submit when first select
    defined and second is visible (i.e. form was refreshed with ajax),
    instead of modal dismiss i see raw output in browser:

  [{"command":"settings","settings":{"basePath":"/","pathPrefix":"","ajaxPageState":{"theme":"opie","theme_token":"5OSo2MbF_rbvJauMUEumH0Mm-gFubWX6Ai-FqvwO9lo"},"fancybox":{"options":{"padding":0,"scrolling":"visible","nextClick":1},"helpers":{"overlay":{"fixed":0}},"selectors":["a[rel=\u0022fancybox\u0022]","a.fancybox","img[rel=\u0022fancybox\u0022]",".gallery-frame
  a"]}},"merge":true},{"command":"modal_dismiss"}]

Can you help me to understand why is that?

Main code:

function modal_callback($mode = NULL) {
    if ($mode == 'ajax') {
        ctools_include('ajax'); ctools_include('modal');
        $form_state = array('ajax' => TRUE, 'title' => 'Title');

        $output = ctools_modal_form_wrapper('stage_form', $form_state);
        if (!empty($form_state['ajax_commands'])) $output = $form_state['ajax_commands'];

        print ajax_render($output); drupal_exit();
    }
    else return drupal_get_form('stage_form');
}

function stage_form($form, $form_state) {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';
    $form['start'] = array(
        '#type' => 'select',
        '#options' => array('1'=>'1', '2'=>'2'),
        '#ajax' => array(
            'callback' => 'form_refresh',
            'wrapper' => 'form-wrapper',
        ),
    );
    if (!empty($form_state['values']['start'])) {
        $form['stop'] = array(
            '#type' => 'select',
            '#options' => array('3'=>'3', '4'=>'4'),
        );
    }
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
}

function form_refresh($form, $form_state) {
    return $form;
}

function stage_form_submit($form, &$form_state) {
    $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
}

I'm not familiar with that ctools command, however try:

$commands = [];

$commands[] = ajax_command_name();

return ['#type' => 'ajax', '#commands' => $commands];

What you ultimately want is for Drupal to receive and render the commands array which should trigger the dismiss and not print the commands to the screen.

(On phone, sorry for formatting)


Drupal Authentication with ActiveDirectory I'm trying to make Drupal work with ActiveDirectory just for authentication. I'm using Lightweight Directory Access Protocol.

I always get this message:

  Warning: ldap_search(): Search: No such object in LdapServer->search() (line 257 of D:\wwwroot\drupal\sites\all\modules\ldap\ldap_servers\LdapServer.class.php).
  Test sandbox-edu LDAP Server Configuration Binding with DN for non-anonymous search (testuser@sandbox.edu). Using password entered in form.
  Successfully bound to server
  Failed to find test user userone by searching on sAMAccountName = user one.
  No such object

Here are the settings of the Server Properties:

sid = SANDBOX_EDU
name = sandbox-edu
status = 1
type = ad
address = LDAP://10.100.100.2
port = 389
tls = 0
bind_method = 1
basedn = Array
binddn = testuser@sandbox.edu
user_dn_expression = cn=%username,%basedn
user_attr = sAMAccountName
mail_attr =
ldap_to_drupal_user =
testing_drupal_username = userone

Can anyone who were able to get this module working with ActiveDirectory show us a sample of the setting?

If there's any other way other than using this module, please also recommend. I really need Drupal to work with ActiveDirectory for authentication because we have many students here.

I have the following set of parameters that allow authentication by Active Directory 2003:

server type: "Active Directory LDAP"
server address: ad.example.com
ldap port: 389
binding method for Searches: Bind with Users Credentials
base DNs for LDAP user entries: cn=users,dc=example,dc=com
username attribute: sAMAccountName
expression for user DN: %username@company.com
email attribute: mail

I think the problem mainly stems from the fact that AD typically does not have the login name in the LDAP DN.


Drupal Views Filter for Slideshow I have created a content type for slide show name as slider in which i have 3 fields

Image, Image Description, and Image Postion(left or right).
I added multiple images and text for this.

Now i want to show slide show according to postion set of each image.

if image is left then it shows to left and text shows to right. and vice versa.

Anybody have idea how to do this

Thanks

This is pretty much a Views theming task.  Hopefully you are familiar with either Firebug or Web Inspector for Chrome. Your "Image Postion Right" and "Image Postion Left" will have their own respective div classes so you can leverage / theme those CSS classes to get the image in the correct postion.

If you need something more powerful beyond this, you may also need to create a Custom Views Template. (In your View, you should see a link for "Theme:Information" -- it might be under "Advanced" if you are using Views 3 for Drupal 7.) Clicking on this will give you template suggestions. You may also need to use the Devel module's "Theme developer" to quickly find the field variable names.-- see this

You also did not say which version of Drupal you are using so there may be some specific things relative to your Drupal version that you will need to be aware of.

So basically as you can see there are multiple ways to do what you need but this should be a good overview and resource. Theming a View is an artform and can take a while to get the hang of but once you do, it's pretty cool.


Exception in worker callback prevents queue item from being removed I have created a Drupal 7 module that utilizes hook_cron() and hook_cron_queue_info() to process some data, as well as use the module Ultimate Cron to handle scheduling when each runs.

hook_cron() is run every 15 minutes and it's job is to determine how much data needs to be processed and split it up into batches, creating a queue for each batch. As an example, say 1000 records, split into batches of 25, so you get 40 queues of 25 records each.

The queue is then processed every minute, so every minute it will process one queue item of 25 records.

The problem I am running into is that occasionally during the worker callback for a queue, when processing one or more of the 25 records, a record may result in an exception being thrown.

The exception is possible and expected, so I am handling the exception in a simple try/catch, so the queue is able to continue on and processes all 25 records. However it seems that if any of the 25 had an exception, the queue item does not get removed at the end like it does when there no problems. Ultimate Cron shows the queue as having started, but never finished and is still running (though really it is not, it got through all 25), and this prevents any further queue items from running.

This is not the behavior I would like, I want the queue item to be removed or "finished" regardless if an exception happened, because I have handled the exception(s).

I am unsure of what is deciding the queue should not be removed, is it drupal's queue api? Ultimate cron? Is there a way I can have it remove the queue manually at the end of the batch if there happened to be an exception?

Basic code:

/**
 * Implements hook_cron().
 */
function MODULENAME_cron() {
  MODULENAME_queue();
}

/**
 * Implements hook_cron_queue_info().
 */
function MODULENAME_cron_queue_info() {
  $queues['MODULENAME_queue'] = array(
    'worker callback' => 'MODULENAME_process_batch',
  );

  return $queues;
}

/**
 * Queue up batches.
 */
function MODULENAME_queue() {
  // Get the queue.
  $queue = DrupalQueue::get("MODULENAME_queue");

  // Only run if there are no items in the queue.
  if (!$queue->numberOfItems()) {
    // Get the full list of records.
    $records = MODULENAME_get_records();

    // Split the list of records into batches to process.
    $pager = 25;
    $batches = array_chunk($records, $pager);

    // Queue the batches.
    foreach ($batches as $batch) {
      $queue->createItem($batch);
    }
  }
}

/**
 * Process a batch.
 */
function MODULENAME_process_batch($data, &$context = NULL) {
  // Process a batch of 25 records.
  foreach ($data as $record) {
    MODULENAME_process_record($record);
  }
}

/**
 * Process a single record.
 */
function MODULENAME_process_record($record) {
  // Processing code here, this is where an exception can happen.
}

I have the same issue. For me putting everyhing inside the worker callback function in a try block solved the issue.


publish article to home page and secondary page I am a joomla convert.  With my old website on Joomla I could publish an article to a specific page as well as the home page.  It would remain on the home page until it was "pushed down" by new articles, but would always be on the specific page in a back up sort of way.  I want to do that here are well.. Let me be a bit more specific...

I have officers at my work place that want to put reports on the website on occasion. When the President posts a report it will post on the front page but also the president page.  I have created a President page on Drupal (7) yet I can't get an article to post to it AND the front page.  I asked this question on another forum and I was rudely directed to look up Taxanomy, which I did and I'm still lost.

Can someone please just direct me to what I need to do to have an article appear on the president page and the home page?

Thank you...

Drupal has a "Promoted to front page" check box under Publishing options when you create a new node.

To use this feature, visit /admin/config/system/site-information and make sure that the field under "Default front page" is empty.  This will enable your front page to show all content with "Promoted to front page" checked.  Anything you promote to the front page will be both on the front page and also have it's own individual page.

If you have a "President" page that needs to show all the president's articles/reports, you should take a look at Views.  This will be one of your best friends and you will want to take the time to learn how to use it properly.  In short, you would use views to create a block that displays articles authored by the president.  You would be able to display the block wherever needed.


Use page.html.twig template variable in another twig template How do I call a page.html.twig template variable from the book-tree.html.twig template.

Using kint, I have found the variable, nid as in the screenshot below:

The 'nid' is highlighted, but it is the 'x-default value that is required.

This variable will be used in a set statement, comparing it to the item.original_link.nid to set an active class.

This page nid is not available within the book-tree.html.twig template.

As per Answer 1, I have created a _preprocess function in my subthemes .theme file as below:

function subtheme_bs_preprocess_book_tree(&$variables) {
 $variables['page_nid'] = 'Add code to get the node id variable';
}

The variable page_nid now shows up in the book-tree.html.twig array. The result is 'page_id' => string(36) "Add code to get the node id variable" which is the static text I added.

I would like help on how to call the nid value from the node.html.twig template. I have tried several combinations:

$variables['page_id'] = $variables['page']['content']['book_navigation']['#book_link']['nid']
But this and many other compinations I have tried all end with a:

Notice: Undefined index: page in subtheme_bs_preprocess_book_tree()

Maybe I need to call an Available method but have no clue as to how this is done.

Below is a screenshot of the {{ kint() }} output from the top of the node.html.twig file.

the value I need to target is the 115 in this line 'x-default' => value (3) 115.

Many thanks in advance.

The book-tree.twig is rendered in its own scope.  It does not "know" any of the context it is being rendered in, so it can't tap into the variables from the page twig per se.  It only gets the variables you give it.  So you could implement a THEME_preprocess_book_tree(&$variables) hook to add it in.  $variables['page_nid'] = // your code here will make it available in twig as {{ page_nid }}.

However at the risk of being "that annoying guy" who tells you not to do things instead of just answering your question

  This variable will be used in a set statement, comparing it to the item.original_link.nid to set an active class.

Personally I would eschew this approach as it ends up placing logic inside the presentation layer.  I would rather use the hook to compare item nids to page nid, and add the active class to that item's attributes as appropriate.  That way the twig can be kept extremely "stupid", and simply dump out whatever attributes for all items, and those attributes will magically contain (or not contain) the appropriate classes.


How to get Product name instead of sku in email to admin in authorize.net? My client has a drupal site where the admin gets a SKU in the confirmation email. He wants to replace that with product name. How can I do that and where do I have to change it?

I found this patch, but I don't see the file in authorize.net module to patch the code.

Can anyone help me out.

Thank You.

You might want to modify uc-order--admin.tpl.php under sites\all\modules\ubercart\uc_order\templateslook for: $product->model (SKU) and comment it out or replace it directly with $product->title , modify the template to your liking but always keep a copy of the original template.


How to create a custom display mode for user in D8? I've created an edito custom content type wich can be linked to a user. I'd like to custom the display with the picture and the name of the user in a view. I don't know how to create a custom display mode for an user.

Any help ?²

You need to create the view mode at Admin > Structure > Display Modes, then configure the new display mode at /admin/config/people/accounts/display.