I'm building a booking calendar module, and want to get back arrival & departure datefields values to highlight reservations on the calendar, passing to a library the variables.

public function showCalendarAction() {       
        return [            
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.popperjs']],
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.bootstrap']],
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.bootstrap_year_calendar']],
            '#markup'=>$this->t('<div data-provide="calendar"></div>')

I intended to store all the dates(linked to one hotel/house) in a json file, that I would call in ajax.

If it's a good Drupal 8 practice, how to do this ?

Else, what would be the good way to store and pass the variables to my module library ?

  • You could also use a module that creates a JSON data storage type for fields. That way it isn't in a physical file on the server. – Kevin Sep 28 '17 at 14:28
  • @Kevin : yes, it does make sense. I tried this too, created a view with my fields, and added a REST export in JSON, then I made an Ajax call to get it back. Works pretty good too. I wonder which solution is best practice ? – GwadaKing Oct 3 '17 at 0:24

You could use the routing system and create a custom route and output your json within the controller.

After that you can load the url in your ajax call.

module.routing.yml (path_to_module/):

  path: '/json-output'
    _controller: '\Drupal\module\Controller\ModuleController::content'

    _permission: 'access content'

ModuleController.php (path_to_module/src/Controller/):


namespace Drupal\module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

 * An example controller.
class ModuleController extends ControllerBase {

   * {@inheritdoc}
  public function content() {
    // Load your json content here.
    $json = module_get_json();

    $response = new Response();
    $response->headers->set('Content-Type', 'application/json');
    return $response;



Now you can load your json via /json-output. It is also possible to pass variables to the controller via the url.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.