Laravel 5.3 pass multiple MessageBag instances to $errors variable - php

I have two modal fields on a page with forms and need to determine which of the model fields is has an error.
So my question is:
How can I pass multiple MessageBag's to $errors to be able check errors using $errors->errorType->get('message')?

I found a solution, it is called "Named Error Bags":
First need to manually create validator: https://laravel.com/docs/5.3/validation#manually-creating-validators
and then create named bag in response;

Related

Dynamically get MessageBag from ViewErrorBag?

In my app, I have a generic place for errors in the view that I display simply using:
show_messages($errors->getMessages());
In the show_messages function I parse out the errors in the way I would like them displayed. However I started using some grouping in my forms like register[email]. When I display the errors I use ->withErrors(Input::get('register'), 'register').
But now I can't dynamically get the messages becasue $errors->getMessages() goes to default message bag by default (which in this case is empty).
I can get the errors using $errors->register->getMessages(), but that's assuming I know it will be register. Looking at the ViewErrorBag class I don't see any methods to provide the bag. Is there anyway to do this without altering the current class to get all the bags dynamically or all the messages in each bag dynamically?
I don't know if this works in Laravel 4, but in Laravel 5 I use $errors->all().
You could simply iterate over all of the object properties.
foreach ($errors as $errorBag) {
show_messages($errorBag->getMessages());
}
While theoretically you would need to check for the property type to know if it's a MessageBag, MessageBag doesn't have any other public properties.

How can I get the form data from the FOSUserBundle registration form?

I am using the FOSUserBundle and have overwritten the RegistrationController. When the form is submitted and valid, I want to get the email address the user entered in the registration form.
But I don't see any way to get it. As taken from the Symfony2 forms documentation, you can get form data like this:
$this->get('request')->request->get('name');
But the RegistrationController does not know the get() method (as it's not inherited from the Symfony2 controller entity). So I could go like this:
// Note the ...->container->...
$this->container->get('request')->request->get('name');
But this returns NULL. Now I try to get it from the $form.
// Does contain a lot of stuff, but not the entered email address
$form->get('email');
// Does also contain a lot of stuff, but not the desired content
$request->get('email');
$request->request('email');
// Throws error message: No method getData()
$request->getData();
Any idea?
It's really, really simple. You create a form with related entity. In FOSUserBundle you should have a RegistrationFormHandler, and in process method you've got:
$user = $this->createUser();
$this->form->setData($user);
if ('POST' === $this->request->getMethod()) {
$this->form->bind($this->request);
if ($this->form->isValid()) /**(...)**/
After the line $this->form->bind($this->request) every value in $user object is overwritten by data from form. So you can use $user->getEmail().
On the other hand you are able to get data directly from request, but not by the property name, but by form name. In FOSUserBundle registration form it is called fos_user_registration - you can find it in FOS/UserBundle/Form/Type/RegistrationFormType.php in getName method.
You get it by:
$registrationArray = $request->get('fos_user_registration');
$email = $registrationArray['email'];
If you were to use Controller as a Service (which should work with this), you could pass the RequestStack (sf >=2.4) in the constructor and do $this->request_stack->getCurrentRequest()->get();
My guess is that you are trying to get the POST data. You are trying to put the data in a form object I presume. I would recommend you to take a look at: http://symfony.com/doc/current/book/forms.html if you have a custom form.
As regarding to your question, the form is probably containing a name. If you want to have direct access to it instead of doing things in your form, you need to fetch it multilevel if directly via the true at $deep, get('registration_form_name[email]', null, true); You can also do $email = $request->get('registration_form_name')['email']; (if you have php 5.4+)

Zend Framework 2 - Removed form element causes validation to fail

I use a certain form in several places. In one of them I need to ignore a form element which I set programmatically after the validation.
Because it's just an exception I don't want to create a new form. So I thought, I just remove this element in the controller like:
$myForm->remove('myElement');
The problem is that the form now won't validate. I don't get any errors but the $myForm->isValid() just returns an empty value.
Any ideas what I might be doing wrong?
Ok, finally I found a solution! You can define a ValidationGroup which allows you to set the attributes you'd like to validate. The others are not validated:
$form->setValidationGroup('name', 'email', 'subject', 'message');
$form->setData($data);
if ($form->isValid()) {
...
The first thing I thought about was to remove the validator from your myElement's ValidatorChain. You could get it within the controller with:
$form->getInputFilter()->get( 'myElement' )->getValidatorChain()
It seems like you can't remove from the ValidatorChain, just add. Check this post. Matthew Weier O'Phinney, from Zend, explains why it can't be done and a possible solution for your scenario.
The way I solve this problem, is checking the 'remove condition' when I create the validator in the FormFilter class. If you use annotations I think it doesn't works for you, so Matthew suggestions is the one you should use.
Or you could try the one in this post from #Stoyan Dimov: define two forms, a kind of BasicForm and ExtendedForm. The first one have all the common form elements, the second one is an extended one of the other with the rest of fields. Depending on your condition you could use one or another.
In class ValidatorChain implements Countable, ValidatorInterface, add a new method:
public function remove($name){
foreach ($this->validators as $key => $element) {
$validator = $element['instance'];
if($validator instanceof $name){
unset($this->validators[$key]);
break;
}
}
}
Use like this:
$form->getInputFilter()->get("xxxxx")->getValidatorChain()->remove('xxxxxx');
There must be a validator defined for this particular element that you are trying to remove.
In your controller where you are adding new elements to form, there must be addValidator calling like:
$element->addValidator('alnum');
That is actually causing validation to be failed. So you have removed the element from form but you still have validation defined on that element to be checked.
If you are not able to find this validation adding function in controller, try to see if it has been defined through config file.
You can read further about form validation in zf here: http://framework.zend.com/manual/1.12/en/zend.form.elements.html
I remove the element with:
$form->get('product')->remove('version');
When I post the form I disable the validator on this element with :
$form->getInputFilter()->get('product')->get('version')->setRequired(FALSE);

Adding a field specific error from the controller in symfony2

I have some complex validation going on with my symfony form, and I need to be able to assign an error to a specific field from my controller. Right now, I have global errors working like this:
$error = new formerror("There is an error with the form");
$form->addError($error);
But that creates a global error, not one bound to a specific field.
Is there a way to throw an error on a specific field from my controller?
Thanks to some help over IRC (thanks #fkrauthan!) I came up with an answer.
Every field in SF2 is actually an instance of form. What you need to do is access the form object of the field, and add then error onto it. Thankfully, symfony provides a method to get an embedded form/field.
Heres my code:
$error = new FormError("There is an error with the field");
$form->get('field')->addError($error);
As some people have pointed out, you will need to include the FormError class at the top of your file:
use Symfony\Component\Form\FormError;

Save multiple tabular input in Yii

I'm wondering how can I insert tabular data in Yii.
Of course, I've followed docs in this aspect however there are few differences in my situation.
First of all, I want to save two models, exactly as in the docs article. The main difference is that there might be more that one element for second model (simple one to many relation in database).
I use CHtml to build my forms. I implemented a jQuery snippet to add more input groups dynamically.
I'm unable to show my code now as it's totally messed up and not working currently.
My main question is: how to handle the array of elements for second model in Yii?
Define your two models in controller
$model1= new Model1();
$model2= new Model2();
//massive assignments
$model1->attributes=$_POST['Model1']
$model2->attributes=$_POST['Model2']
//validation
$valid= $model1->validate();
$valid =$valid && $model2->validate();
if($valid){
$model1->save(false);
$model1->save(false);
}
if you want to access fields individually dump your post and you can view the the
post array format or instead of doing massive assignments you can manually assign like this
$model1->field1 =$_POST['Model1']['field1'];
//validation logic
...
if($valid){
$model1->save(false);
$model1->save(false);
}

Categories