Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

php - Symfony 2 - how to pass data to formBuilder?

I'm using entity choice list in my form. I want to use only specific entities (in example: only groups that user belongs to) So, in controller, I'm getting these groups, and trying to pass them into formBuider.

Controller:

/.../
$groups = $em->getRepository('VendorMyBundle:Group')->getUserGroups($user);
$form = $this->createForm(new Message($groups), $message);
/.../

so, what now? how to use it in formBuilder? how to change this line to use passed array of groups?

->add('group','entity',array('class' => 'VendorMyBundleEntityGroup', 'label'=>'Group:'))

or in the other way:

class MessageType
{
/.../
  public function buildForm(FormBuilder $builder, array $options)
  {
    $builder
      ->add('group','entity',
        array(
          'class' => 'VendorMyBundleEntityGroup',
          'property' => 'name',
          'query_builder' => function ($repository) {
            $qb = $repository->createQueryBuilder('group');
            $qb->add('where', 'group.administrator = :user');
            $qb->setParameter('user', $user->getId());
            return $qb;
          },
          'label' => 'Group'
        )
      )
      // Continue adding fields
    ;
  }
/.../
}

so how can i get object $user to use in form builder? ($user represent current logged user)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can give the object you want to use in the __construct() method.

Eg :

$form = $this
    ->get('form.factory')
    ->create(new ApplyStepOneFormType($this->company, $this->ad), $applicant);

In your form type :

function __construct(YourBundleEntityCompany $company, DYBConnectBundleEntityAd $ad) {
    $this->company = $company;
    $this->ad = $ad;
}

And then in your form type in buildForm method :

$company = $this->company;    
$builder->add('ad', 'entity', array(
    'class' => 'YourBundleEntityAd',
    'query_builder' => function(YourBundleRepositoryAdRepository $er) use ($company) {
        return $er->getActiveAdsQueryBuilder($company);
    },
));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...