Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [Symfony2][Form]Jak przekazać parametr do formularza
Forum PHP.pl > Forum > PHP > Frameworki
silverwind
Chce aby przy dodawaniu expenses w fromularzu można wybrać tylko zalogowanego Użytkownika tylko nie wiem jak wstrzyknąć parametr ($User) w formcreatebuilder.
Mój controler
  1. public function newAction(Request $request)
  2. {
  3.  
  4. $User = $this->getUser()->getUsername();
  5.  
  6. $expense = new Expenses();
  7. $form = $this->createForm(ExpensesType::class, $expense,r);
  8. $form->handleRequest($request);
  9.  
  10. if ($form->isSubmitted() && $form->isValid()) {
  11. $em = $this->getDoctrine()->getManager();
  12. $em->persist($expense);
  13. $em->flush();
  14.  
  15. return $this->redirectToRoute('expenses_index');
  16. }
  17.  
  18. return array(
  19. 'expense' => $expense,
  20. 'form' => $form->createView(),
  21. );
  22. }

formtype

  1. public function buildForm(FormBuilderInterface $builder, array $options)
  2. {
  3.  
  4. $builder
  5. ->add('name', TextType::class, array(
  6. 'label' => 'Nazwa wydatku'))
  7. ->add('price', MoneyType::class, array(
  8. 'label' => 'Cena',
  9. 'currency' => 'false'
  10. ))
  11. ->add('createDate', DateType::class, array(
  12. 'label' => 'Data'
  13. ))
  14.  
  15. ->add('property', 'entity', array(
  16. 'label' => 'Nieruchomość',
  17. 'class' => 'User\UserBundle\Entity\User',
  18. 'property' => 'adress',
  19. 'empty_value' => 'Wybierz adres',
  20. 'query_builder' => function(UserRepository $repository) use($User)
  21. { return $repository->getQueryBuilder($User);}
  22.  
  23. ))
  24.  
  25.  
  26. ->add('submit', SubmitType::class, array(
  27. 'label' => 'Dodaj',
  28. ))
  29. ;
  30. }
  31.  
  32. /**
  33.   * @param OptionsResolver $resolver
  34.   */
  35. public function configureOptions(OptionsResolver $resolver)
  36. {
  37. $resolver->setDefaults(array(
  38. 'data_class' => 'Property\ManagementBundle\Entity\Expenses'
  39. ));
  40. }
kpt_lucek
  1.  
  2. /**
  3.  * @param User|null $user
  4.  */
  5. private $user;
  6.  
  7. public function __construct(User $user = null)
  8. {
  9. $this->user = $user;
  10. }
  11.  
  12. public function buildForm(formBuilderInterface $formBuilder, $options)
  13. {
  14. //....
  15. ->add('user', 'EntityType', array(
  16. 'label' => 'User',
  17. 'class' => User::class
  18. 'property' => 'xyz',
  19. 'data' => $this->user
  20. ));
  21. }
  22.  



Pisane z palca
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.