Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [Symfony2][SF][SF2] Pole w formularzu, które stworzy obiekt
Fluke
post
Post #1





Grupa: Zarejestrowani
Postów: 247
Pomógł: 9
Dołączył: 20.09.2010
Skąd: Kraków

Ostrzeżenie: (0%)
-----


Witam,

Mam pytanie odnośnie pojedynczego pola w formularzu, które po uzupełnieniu stworzy mi obiekt danego typu.
Mam encję Person z polami: [id, firstname, lastname, email, address]
Formularz:
  1. $builder->add(
  2. 'email',
  3. 'email',
  4. [
  5. 'property_path' => 'person.email',
  6. 'data_class' => Person::class,
  7. ]
  8. );

I w ten sposób chciałbym, żeby mi stworzyło encję typu Person z uzupełnionym polem email. Niestety dostaję: Expected argument of type "object or array", "NULL" given.

Jest sposób na to aby automatycznie w Symfony2 stworzył mi taką encję ? Zaznaczę, że próbowałem jeszcze z "empty_data" który zwracał obiekt Person ale też nie działa. Też chciałbym nie używać DataTransformer.

Pozdrawiam.
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
Fluke
post
Post #2





Grupa: Zarejestrowani
Postów: 247
Pomógł: 9
Dołączył: 20.09.2010
Skąd: Kraków

Ostrzeżenie: (0%)
-----


Do tego zrobiłem sobie klasę:

  1. class CustomType extends AbstractType {
  2. /**
  3.   * @var string
  4.   */
  5. protected $name;
  6.  
  7. /**
  8.   * @var callable
  9.   */
  10. protected $callback;
  11.  
  12. /**
  13.   * @var array
  14.   */
  15. protected $defaults;
  16.  
  17. /**
  18.   * @param string $name
  19.   * @param callable $callback
  20.   * @param array $defaults
  21.   */
  22. function __construct($name, $callback, array $defaults = []) {
  23. $this->name = $name;
  24. $this->callback = $callback;
  25. $this->defaults = $defaults;
  26. }
  27.  
  28. /**
  29.   * @param FormBuilderInterface $builder
  30.   * @param array $options
  31.   */
  32. public function buildForm(FormBuilderInterface $builder, array $options) {
  33. call_user_func_array($this->callback, [$builder, $options]);
  34. }
  35.  
  36.  
  37. /**
  38.   * @param OptionsResolverInterface $resolver
  39.   */
  40. public function setDefaultOptions(OptionsResolverInterface $resolver) {
  41. $resolver->setDefaults($this->defaults);
  42. }
  43.  
  44. /**
  45.   * @return string The name of this type
  46.   */
  47. public function getName() {
  48. return $this->name;
  49. }
  50. }


I mogę teraz używać w ten sposób:
  1. new CustomType('my_custom_form', function ($builder, $options) {
  2. $builder->add('firstname', 'text);
  3. $builder->add('lastname', 'text');
  4. }, ['data_class' => User::class]);
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 26.12.2025 - 13:45