tattali / CalendarBundle

Provides event calendar for your Symfony project. Compatible with API like Google Calendar.

Home Page:https://packagist.org/packages/tattali/calendar-bundle

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Filters getting

dubitoph opened this issue · comments

Hello,

I use Symfony 4..2.1.

I meet a problem when I try to get the filters. I implement the filter variable in the javascript like this :
` eventSources: [
{

                            url: "/fc-load-events",
                            type: "POST",
                            data: {

                                    filters: {"vehicle": 1},

                                },
                            error: () => {

                                            alert("There was an error while fetching FullCalendar!");

                                         },

                        },
                      ],`

In my listener, I get the filters with $filters = $calendar->getFilters();. When I try to get the specific filter with $vehicle = $filters['vehicle'];, I have this error :

"Notice: Undefined index: vehicle"

Hello, I am sending a new release to solve your problem.
Fullcalendar has changed its syntax to get events.

https://fullcalendar.io/docs/events-json-feed

- type: "POST",
- data: {
-     filters: {},
- },
- error: () => {},
+ method: "POST",
+ extraParams: {
+     filters: JSON.stringify({}),
+ },
+ failure: () => {},

do not forget to update to 1.1.4

@dubitoph which fullcalendar version do you have ?

Thank you very much for your reactivity.

I'm using version 4.

I updated to the 1.1.4 version and I changed the javascript like you said.

However, I have a new error in \vendor/tattali/calendar-bundle/src/Controller/CalendarController.php (line 37). It's this line code :

$start = new \DateTime($request->get('start'));

There is my javascipt :

`
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/timegrid/main.css';
import '@fullcalendar/list/main.css';

import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';

export default class ShowCalendar {

static init () 
{

    

    var calendarEl = document.getElementById('calendar-holder');

    if (calendarEl === null) 
    {

        return;

    }

    var calendar = new FullCalendar.Calendar(calendarEl, {

        defaultView: 'dayGridMonth',
        editable: true,
        eventSources: [
                        {

                            url: "/fc-load-events",
                            method: "POST",
                            extraParams: {
                            filters: JSON.stringify({ vehicle: 1 }),
                            },
                            failure: () => {},

                        },
                      ],
        header: {

                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay',

                },
        plugins: [ dayGridPlugin, timeGridPlugin, listPlugin ], // https://fullcalendar.io/docs/plugin-index
        timeZone: 'UTC',

    });

    calendar.render();

}

}
`

My listener :

`<?php

namespace App\Listener;

use App\Entity\Booking;
use CalendarBundle\Entity\Event;
use App\Repository\BookingRepository;
use CalendarBundle\Event\CalendarEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class CalendarListener
{
private $bookingRepository;
private $router;
private $sessionManager;
private $securityContext;

public function __construct(BookingRepository $bookingRepository, UrlGeneratorInterface $router) 
{

    $this->bookingRepository = $bookingRepository;
    $this->router = $router; 

}

public function load(CalendarEvent $calendar): void
{
    
    $start = $calendar->getStart()->format('Y-m-d H:i:s');
    $end = $calendar->getEnd()->format('Y-m-d H:i:s');

    $filters = $calendar->getFilters();

// $vehicle = null;

    $vehicle = $filters['vehicle']; 

// if (!empty($filters))
// {
// if (array_key_exists('vehicule', $filters))
// {

// $vehicule = $filters['vehicule'];

// }
// }

    $bookings = $this->bookingRepository->findBetweenDates($start, $end, $vehicle);

    foreach ($bookings as $booking) 
    {

        // this create the events with your data (here booking data) to fill calendar
        $bookingEvent = new Event(
                                    $booking->getTitle(),
                                    $booking->getBeginAt(),
                                    $booking->getEndAt() // If the end date is null or not defined, a all day event is created.
                                 )
        ;

        /*
         * Add custom options to events
         *
         * For more information see: https://fullcalendar.io/docs/event-object
         * and: https://github.com/fullcalendar/fullcalendar/blob/master/src/core/options.ts
         */

        $bookingEvent->setOptions([
                                    'backgroundColor' => 'red',
                                    'borderColor' => 'red',
                                  ]
                                 )
        ;

        $bookingEvent->addOption(
                                    'url',
                                    $this->router->generate('admin.booking.show', ['id' => $booking->getId(),])
                                )
        ;

        // finally, add the event to the CalendarEvent to fill the calendar
        $calendar->addEvent($bookingEvent);

    }

}

}`

And my BookingRepository :

`<?php

namespace App\Repository;

use App\Entity\Booking;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**

  • @method Booking|null find($id, $lockMode = null, $lockVersion = null)

  • @method Booking|null findOneBy(array $criteria, array $orderBy = null)

  • @method Booking[] findAll()

  • @method Booking[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    */
    class BookingRepository extends ServiceEntityRepository
    {
    public function __construct(RegistryInterface $registry)
    {
    parent::__construct($registry, Booking::class);
    }

    /**

    • @return Booking[]
      */
      public function findBetweenDates($start, $end, $vehicleId)
      {

      return $this->createQueryBuilder('b')
      ->where('b.beginAt BETWEEN :start and :end')
      ->where('b.vehicle = :vehicleId')
      ->setParameter('start', $start)
      ->setParameter('end', $end)
      ->setParameter('vehicleId', $vehicleId)
      ->getQuery()
      ->getResult()
      ;
      }

    // /**
    // * @return Booking[] Returns an array of Booking objects
    // /
    /

    public function findByExampleField($value)
    {
    return $this->createQueryBuilder('b')
    ->andWhere('b.exampleField = :val')
    ->setParameter('val', $value)
    ->orderBy('b.id', 'ASC')
    ->setMaxResults(10)
    ->getQuery()
    ->getResult()
    ;
    }
    */

    /*
    public function findOneBySomeField($value): ?Booking
    {
    return $this->createQueryBuilder('b')
    ->andWhere('b.exampleField = :val')
    ->setParameter('val', $value)
    ->getQuery()
    ->getOneOrNullResult()
    ;
    }
    */
    }
    `

If I remove the setting vehicleId parameter in the bookingRepository function, I don't have any error :

` /**
* @return Booking[]
*/
public function findBetweenDates($start, $end, $vehicleId)
{

    return $this->createQueryBuilder('b')
                        ->where('b.beginAt BETWEEN :start and :end')

// ->where('b.vehicle = :vehicleId')
->setParameter('start', $start)
->setParameter('end', $end)
// ->setParameter('vehicleId', $vehicleId)
->getQuery()
->getResult()
;
}`

What is the error message and which parameters are sended in the POST request

You should probably

- var calendar = new FullCalendar.Calendar(calendarEl, {
+ var calendar = new Calendar(calendarEl, {

because else import { Calendar } from '@fullcalendar/core'; is not used

I tried this :

In the js :

` var calendar = new Calendar(calendarEl, {

        defaultView: 'dayGridMonth',
        editable: true,
        eventSources: [
                        {

                            url: "/fc-load-events",
                            method: "POST",
                            extraParams: {
                            filters: JSON.stringify({ vehicle: vehicleId }),
                            },
                            failure: () => {},

                        },
                      ],

...`

In the listener :

` $filters = $calendar->getFilters();

    $vehicle = null;
    
    if (!empty($filters))
    {
        if (array_key_exists('vehicle', $filters))
        {

            $vehiculeId = $filters['vehicle']; 

            $vehicle = $this->bookingRepository->find($vehiculeId);
            
		}
	} 

    $bookings = $this->bookingRepository->findBetweenDates($start, $end, $vehicle);`

In the repository :

` /**
* @return Booking[]
*/
public function findBetweenDates($start, $end, Vehicle $vehicle = null)
{

     $query = $this->createQueryBuilder('b')
                  ->where('b.beginAt BETWEEN :start and :end');

    if (!empty($vehicle))
    {

        $query->andWhere('b.vehicle = :vehicle');

    }					

    $query->setParameter('start', $start)
          ->setParameter('end', $end);

    if (!empty($vehicule))
    {

        $query->setParameter('vehicle', $vehicle);

    }
    
    return $query->getQuery()
                 ->getResult()
    ;
}`

I have this error :

DateTime::__construct() expects parameter 1 to be string, null given

Attached, 3 files with console logs :
Capture
Capture2
Capture3

do you have empty start date in your database?

Currently, I have only one recording in the table booking. There is a screen shot.
Capture

I replaced $vehicle = $this->bookingRepository->find($vehiculeId); by $vehicle = $this->vehicleRepository->find($vehiculeId); because that was a mistake.

However, I alwayshave the same message and there is he message in the network panel.
Capture

In the repository, I set 3 parameters.

` $query->setParameter('start', $start)
->setParameter('end', $end);

    if (!empty($vehicule))
    {

        $query->setParameter('vehicle', $vehicle);

    }`

There is certainly a problem with the parameter from filters.

Sorry, the mistake comes from this : if (!empty($vehicule)). This is if (!empty($vehicle))

ok you still have another error?

All is in order now. Sorry for my inattention and thank your very much for your help.

It was a pleasure if you want thank do not forget to star the bundle.

and if I may you should use a linter to facilitate reading

Star given ;).

What's a linter?

This is a software that automatically "beautify" your code to follow language standards.
This is very useful when you share code with other people.

Here are some interesting links for PHP:

Ok, thank you!