1

I have a problem with the validation of Symfony. I have a form which is of the type User and the user maps some other stuff (like Addresses, Phones etc.)

Now I want to force the creator of the user that he makes one of the Addresses/Phones the primary one (the entity has a field for that).

How can I solve this? So only one of the OneToMany Entitys (one of the Addresses) needs to be a primary one. And assure that it will be always at least one.

1 Answer 1

1

One way is to add a field to the User entity pointing to a primary address in a one-to-one manner and make it required.

Another way is to create a custom validator that will loop through the user addresses and validate that at least one of them is marked as primary.

Or you could just use the True constraint:

/**
 * @True
 */
public function isThereOnePrimaryAddress()
{
    $primes = 0;
    foreach ($this->getAddresses() as $address) {
        if ($address->isPrimary()) {
            $primes++;
        }
    }

    if (1 === $primes) {
        return true;
    }

    return false;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I thought so. But how do I create a custom validator — which can loop through the form, or all the primary markers. And not just one attribute?
Okay I found the answer to this question, or at least I did it like this: /** * @Assert\True(message="auth.valid.addresses.oneprime") */ public function isThereOnePrimaryAddress() { $primes = 0; foreach($this->getAddresses() as $address) if($address->getPrimaryAddress() == true) $primes++; if($primes === 1) return true; return false; } Sorry, but I am not able to post it formatted. Please edit it if you can.
Could you then insert this Code formatted into your answer for other users who may experience the same problem? Of course only if you are in compliance with my used solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.