#! code: Drupal 10: Using A Lazy Builder To Create A Dynamic Button
Adding dynamic and interactive elements to a web page can be a challenge, and there are a few techniques available in Drupal to allow for this.
One solution might be to add a form to the page, but this can cause problems with the cache system. Adding forms actually makes it slightly difficult to cache the page properly and you can easily see poor caching levels from pages containing forms.
Rather than adding a form to the site (and the complexities that come with that) it is possible to create a fully dynamic element that can be used to perform actions by the user. This is done using a combination of different techniques, all of which are built into Drupal and just need to be plugged together.
In this article I will look at using lazy builders to create a dynamic button that won't cause problems with the page cache, and will even work for anonymous users.
The Problem
For some context I thought I would talk about some of the work that went into putting this example together.
I was recently tasked to create a button on an Event content type that would act as the registration action for that event. The button needed to take into account different factors like the role of the user, the type of event, and the remaining capacity of the room. When the user clicked on the button they would be booked onto the event and the content of the button would change to inform them of this.
The button, therefore, needed to be fully dynamic for the user and the page they were visiting. In order to allow the button to be unique to each user and event I used a lazy builder to offset the generation of the button so that it wouldn't interfere with the caching of the page.