سؤال

I want to set up a functionnality on user registration: user can enter a coupon code that has been previously generated and stored in a table. The field appears along with the user registration form. If they enter a code that doesn't exist, the form shoudln't validate, an error message should appear telling them the code is invalid. What is the best practise to achieve this?

My problem is that the coupon field isn't linked to the User entity. I can check the coupon code's validity with ajax and only validate the form if the code exists or the field is empty. But if I proceed like this, how can I access the coupon code data in my RegistrationFormHandler? The aim is to give special priviledge to User who entered a valid code.

Is this a good way to do at all?

هل كانت مفيدة؟

المحلول

In your form add a text field with a false property_path:

$builder->add('coupon', 'text', array('property_path' => false));

Validate it either using ajax or a custom event subscriber (I would prefer the latter). The in your controller It should be enough to check if the form is valid:

if('POST' === $request->getMethod()) {
    $form->bindRequest($request);
}

if('GET' === $request->getMethod() && $form->isValid()) {
    // Here both user and coupon are valid
    $coupon = $form->get('coupon')->getData();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top