我试图找到Symfony的脚,并且在幕后继承了许多Symfony类,我很难知道我有时会处理什么。我发现我经常磕磕碰碰地知道$variables
是否是字符串/数组/实体/对象。
有人可以提供一些规则或指导,以了解正在处理哪些内容以及如何处理$variable
?
例如,在最后的FormType
类中,我发现很难看到正在播放的字符串/数组/实体/对象。
我的尝试是:
UserType class (child of AbstractType)
// function buildForm
˪$builder object (instantiated by FormBuilderInterface)
˪$options array
˪$Firstname string
˪$owner object (instantiated by AppBundle:Owner entity)
˪class array element
˪choice_label array element
˪query_builder array element
˪$er object (instantiated by EntityRepository)
˪array $o (contains elements for database query result)
˪$onPreSetData object (instantiated by FormEvents::PRE_SET_DATA)
˪$onPreSubmit object (instantiated by FormEvents::PRE_SUBMIT)
// function addElements
˪$form object (instantiated by FormInterface)
˪$post object (instantiated by AppBundle:Post entity)
˪class array element
˪choice_label array element
˪query_builder array element
˪$er object (instantiated by EntityRepository)
˪array $o (contains elements for database query result)
// function onPostSubmit (similar for onPreSubmit)
˪$event object (instantiated by FormEvent)
˪$form object (instantiated from '$this' object)
˪$data object (instantiated from '$this' object)
代码我指的是:
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('Firstname')
->add('owner','entity',array(
'class'=>'AppBundle:Owner',
'choice_label'=>'username',
'query_builder'=>function(EntityRepository $er) {
return $er->createQueryBuilder('o')
->orderBy('o.username','ASC');
}));
// Add listeners for Post field
$builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
$builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
}
protected function addElements(FormInterface $form, $owner = null)
{
if($owner){
$form->add('post','entity',array(
'class'=>'AppBundle:Post',
'choice_label'=>'posttext',
'query_builder'=>function(EntityRepository $er) {
return $er->createQueryBuilder('p')
->join('p.owner', 'o')
->where('o.id = :ownerID')
->setParameter('ownerID', $owner->getID() )
->orderBy('d.postdate','ASC');
}));
}
}
public function onPreSubmit(FormEvent $event)
{
$form = $event->getForm();
$data = $event->getData();
$this->addElements($form, $data->getOwner());
}
public function onPreSetData(FormEvent $event)
{
/** @var User user */
$user = $event->getData();
$form = $event->getForm();
$this->addElements($form, $user->getOwner());
}
}