1

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 ?

2
  • 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
    Commented Sep 28, 2017 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
    Commented Oct 3, 2017 at 0:24

1 Answer 1

1

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/):

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

  requirements:
    _permission: 'access content'

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

<?php

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->setContent($json);
    $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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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