Skip to content

Instantly share code, notes, and snippets.

@khepin
Created October 16, 2012 03:47
Show Gist options
  • Save khepin/3897139 to your computer and use it in GitHub Desktop.
Save khepin/3897139 to your computer and use it in GitHub Desktop.
<?php
namespace Acme\WhateverBundle\FormSubscriber;
use Symfony\Component\Form\Event\DataEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
use Doctrine\ODM\MongoDB\DocumentRepository;
use Symfony\Component\Security\Core\SecurityContext;
/**
* Only add user's friends as possible choices
*/
class OrganizerEventsListener implements EventSubscriberInterface
{
/**
* @var FormFactoryInterface
*/
private $factory;
private $user;
/**
* @param factory FormFactoryInterface
*/
public function __construct(FormFactoryInterface $factory, SecurityContext $security_context)
{
$this->factory = $factory;
$this->user = $security_context->getToken()->getUser();
}
public static function getSubscribedEvents()
{
return [FormEvents::PRE_SET_DATA => 'preSetData'];
}
/**
* @param event DataEvent
*/
public function preSetData(DataEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
$user_id = $this->user->getId();
$form_options = [
'class' => 'Acme\WhateverBundle\Document\User',
'multiple' => false,
'expanded' => false,
'property' => 'title',
'query_builder' => function(DocumentRepository $dr) use ($user_id) {
return $dr->createQueryBuilder()->field('friends.$id')->equals(new \MongoId($user_id));
}
];
$form->add($this->factory->createNamed('friend', 'document', null, $form_options));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment