1

I'm building a REST API with Symfony. Let's say I've got the following Doctrine entity:

class Car {
    private $model;
    private $make = 'Mercedes';
    /** @Assert\NotBlank() **/
    private $year;
}

When I try to create a new Car with an HTTP POST request (REST, no browser), if the request doesn't contain any value for the $make property, by default the Form::submit() method nullifies this field in my entity. As I don't want it to do so, I set its clearMissing argument to false. This works fine except now my @Assert constraints are not taken into account (as opposed to when clearmissing is true). For instance the $year property doesn't trigger any error if null, it looks looks like no validation is performed

So I'd like to know if there is a way to have:

  • properties with default values on my entity
  • plus no field nullification for missing data
  • plus @Asserts constraints respected

Note:

I found a two year old issue on Github which describes my problem exactly, but the problem is supposed to be fixed. So it shouldn't be the same as mine...

marcv
  • 1,874
  • 4
  • 24
  • 45

1 Answers1

1

According to http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html :

  1. If you want to use default value, you can use next:

1) for YAML:

field:
    options:
        default: "your_value_here"

2) for annotations just add to @ORM\Column next:

options={default:"you_value_here"}
  1. to set nullable just add nullable: true option:

1) YAML

field:
    nullable: true

2) annotations

@ORM\Column(...., nullable=true)
Sergio Ivanuzzo
  • 1,820
  • 4
  • 29
  • 59
  • This will only affect database level. I'd like my objects to have this default value (without having to repeat the default value in the php property as well, because DRY). – marcv Nov 12 '15 at 17:07
  • @marcv have you tried to initialize your object in __construct()? – Sergio Ivanuzzo Nov 12 '15 at 17:17
  • Yes, it makes no difference as compared to `private $myProperty = 'value'`. It gets nullified by `submit()` if the `clearMissing` arg is true. – marcv Nov 12 '15 at 17:58
  • @marcv I've tested defining of property and it works for me. So, I set `private $myProperty` to `value` in my Entity class and then use `$form->handleRequest();` As result I get predefined value in my form and save it successfully. What are you using for submit ? – Sergio Ivanuzzo Nov 12 '15 at 18:16
  • I cannot use handleRequest (AFAIK) because I'm in a REST context. The request doesn't come from a browser. My form's name is not in the request, for example, which is something `handleRequest()` expects. I use `$form->submit($request, true/false)` – marcv Nov 12 '15 at 18:19
  • @marcv see also [this](https://github.com/FriendsOfSymfony/FOSRestBundle/issues/585) – Sergio Ivanuzzo Nov 12 '15 at 18:23