<?php

/*
 * This file is part of the FOSUserBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AppBundle\Form;

use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;

class FormationsType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('formation', CollectionType::class, array(
            'entry_type'=> FormationType::class,
            'prototype'=>true,
            'allow_add'=>true,
            'allow_delete'=>true
        ));

        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            $submittedData = $event->getData();
            if (!array_key_exists('formation', $submittedData)) {
                return;
            }
            usort($submittedData['formation'], "static::sortByBeginYearFormation");
            $event->setData($submittedData);
        });
    }
    
    private static function sortByBeginYearFormation($x, $y) {
        
        return strcasecmp($y['beginYearFormation'], $x['beginYearFormation']);
    }

    public function getName()
    {
        return 'formations';
    }
}
