Laravel - highlighting the confirmation field for an error - validation

I can't find a way to get Laravel to highlight the correct field when a _confirmation field is incorrect.
Using a Bootstrap layout I've got an email and email_confirmation field in my form like this:
<div class="control-group {{$errors->has('email') ? 'error' : ''}}">
{{ Form::label('email', 'Email', array('class' => 'control-label'))}}
<div class="controls">
{{ Form::email('email', Input::old('email'));}}
{{ $errors->first('email', Form::block_help(':message')) }}
</div>
</div>
<div class="control-group {{$errors->has('email_confirmation') ? 'error' : ''}}">
{{ Form::label('email_confirmation', 'Confirm Email', array('class' => 'control-label'))}}
<div class="controls">
{{ Form::email('email_confirmation', Input::old('email_confirmation'));}}
{{ $errors->first('email_confirmation', Form::block_help(':message')) }}
</div>
</div>
So if the user puts in an invalid email address then the 'email' field will have an error attached to it and the correct label/field will be highlighted.
But if the user has entered a valid/correct email address in the first field but gets the confirmation wrong - the error returned is still for the 'email' field, not the email_confirmed field.
To me it looks weird when the email field is highlighted when the error is actually with the email_confirmation field.
As far as I can understand from this stackoverflow question, I could probably do something like
{{$errors->first('email', ':message') == 'Please confirm your email address correctly.' ? 'error' : ''}}
This will work, but the problem is that I'm running a multi-lingual site so the :message that gets returned is going to be one of many possibilities.
I guess I could write a function to compare the :message against an array of messages for each language but I thought I'd check if there was an easier way to go about it.
Cheers!

This is how I show an inline error if the title field is empty:
<div class="form-group #if ($errors->has('title')) has-error #endif">
{{ Form::label('title', 'Title') }}
{{ Form::text('title', null, array('class' => 'form-control')) }}
#if ($errors->has('title')) <p class="help-block">{{ $errors->first('title') }}</p> #endif
</div>
And my validation rule:
public static $rules = array(
'title' => 'required',
);
Using Laravel 4 and Bootstrap 3.

Or you could just print all the Error messages somewhere
$messages = $validator->messages();
echo '<ul>';
foreach ($messages->all() as $message)
{
echo '<li>'.$message.'</li>';
}
echo '</ul>';

Related

Add parameter to submit form laravel

here you can see my form where I put in a username and have a hidden idgroup field.
{!! Form::open(array('route'=>'create.invitation')) !!}
<div class="form-group">
{{Form::label('username', 'Username')}}
{{Form::text('username', '', ['class' => 'form-control', 'placeholder' => 'Enter Username'])}}
<input type="hidden" name="idgroup" value="{{$group}}"/>
{{ csrf_field() }}
</div>
<div>
{{Form::submit('Submit',['class' => 'btn btn-primary'])}}
<a class="btn btn-default btn-close" href="{{ route('home') }}">Cancel</a>
</div>
{!! Form::close() !!}
After that this route leads me to my controller function
Route::post('invitation/show', 'InvitationController#create')->name('create.invitation');
How can I add the username and the idgroup to my url?
My problem is now when I click submit I get back this url http://127.0.0.1:8000/invitation/create and when I click enter to the url line I get an error no message because no parameter will pass to the function.
Add. Here is the function
public function create(Request $request)
{
$request->validate([
'username' => [
'required', 'alpha_num', new ExistingUser, new UserNotAdmin
]
]);
$username = $request->username;
$iduser = User::where('name', $username)->select('id')->first();
$group = $request->idgroup;
return view('invitation.overview')->with('group', $group)->with('iduser', $iduser);
}
You cannot pass parameter inside POST body without submitting a form.
But you can try to allow both GET or POST by using any() for the route, so you can test the page around.
Route::any('invitation/show', 'InvitationController#create')->name('create.invitation');
And then, you can try pass variable through queries inside URL
http://127.0.0.1:8000/invitation/create?username=something&idgroup=1

Laravel error "Missing required parameters for Route" when I use a form with a foreach loop

Missing required parameters for [Route: templates.answers.store] [URI: templates/{template}/answers]. (View: D:\Applications\xampp\htdocs\clientpad\resources\views\templates\answers.blade.php)
I am having the above error when I try and use a form with my foreach loop. I am not even sure why this is happening, maybe because I am new at Laravel. But this error goes away once I get rid of the AnswerController#store from the Eloquent form. It is possible I am doing this whole form wrong.
Here is what I want to do: A user made a template with questions, on the click of use button which goes to this url: http://clientpad.test/templates/{id}/answers they see their made questions which are shown with a foreach loop. Around it a Form is made so a user can answer the questions made. The form and answer field shows when I delete the action AnswerController#store, otherwise I get the above error.
Here is the code:
AnswerController:
public function index(Template $template, Question $question)
{
$questions = $template->questions->mapWithKeys(function($question){
return [$question->id => $question->question];
});
return view('templates.answers')->with('template', $template)->with('questions',$questions);
}
public function store(Request $request, Question $question, Answer $answer)
{
$answers = new Answer;
$answers->answer = $request->input('answer');
$answers->question_id = $request->input('question_id'); //current template id
$question->answers()->save($answers);
dd($question);
return redirect('/dashboard')->with('success', 'Your Question Was Successfully Created');
}
answers.blade.php
{!! Form::open(['action' => 'AnswersController#store', 'method' => 'POST']) !!}
#foreach ($questions as $question) <!-- Index counts the questions shown -->
<div class="panel panel-default">
<div class="panel-body">
<p class="pull-left question2"> {{$question}}</p>
<div class="form-group answer">
{{Form::label('', '')}}
{{Form::text('answer', '', ['class' => 'form-control', 'placeholder' => 'Type in your answer'])}}
</div>
</div>
</div>
#endforeach
<hr>
{{Form::submit('Save', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
And I am just using the resource in routes.
Your are calling a route templates/{id}/answers in your Blade view that is missing the {id} parameter. Reading the error thoroughly will help you understand.
Instead of writing:
Form::open(['action' => 'AnswersController#store', 'method' => 'POST'])
You write:
Form::open(['action' => ['AnswersController#store', $template_id], 'method' => 'POST'])
The $template_id will fill the {id} in your route URL templates/{id}/answers.

Combine Form::text and error check into one?

In the blade view file, I have something like this:
{{ Form::text('contact_name', null, ['class' => 'form-control']) }}
#if ($errors->has('contact_name'))
<div class="error-block">{{ $errors->first('contact_name') }}</div>
#endif
{{ Form::text('contact_email', null, ['class' => 'form-control']) }}
#if ($errors->has('contact_email'))
<div class="error-block">{{ $errors->first('contact_email') }}</div>
#endif
When user press submit, it will check inputs validation in the controller. However, if there is an error with the validation, it will then redirect back to a form and populate it with error messages {{ $errors->first() }}
Is there a way to exclude {{ $errors->first() }} in the view file and still show error messages if validation failed? So combine Form::text and $errors->hasinto one function or something like that?
Use a Form Macro to do this
Form::macro('myText', function($field)
{
$string = Form::text($field, null, ['class' => 'form-control']);
if ($errors->has($field)) {
$string .= $errors->first($field);
}
return $string;
});
Then in your view
{{ Form::myText('contact_email') }}

How to save post form in Laravel-4

I am creating parent email form in this form parent insert his email id.
I facing problem is when I submit form that showing error ,Method [save] does not exist
and my code is
registration form
<div class="form">
{{ Form::open(array('url' => '/api/v1/parents/registration_step_2', 'class' => "worldoo-form form form-horizontal", 'id' => "signupForm", 'method' => "post" )) }}
<div class="form-group ">
{{ Form::label('cemail', 'Please enter your parents e-mail:', array('class' => "control-label"));}}
<div class="">
{{ Form::email('cemail', '', array('class' => "form-control", 'id' => "cemail"));}}
<i class="sprite success form-control-feedback"></i> </div>
<h5 class="regular-font text-left">Your parents will need to activate your account before you can access worldoo.</h5>
</div>
<div class="form-group">
<div class="text-center">
{{Form::submit('Next', array('class' => "btn btn-primary"));}}
</div>
</div>
{{ Form::close() }}
</div>
my controller
public function registrationStepTwo()
{
$cemail = $_REQUEST['cemail'];
if($cemail != '')
{
$parent = new Parent;
$parent->email = $cemail;
$parent->save();
}
}
I had the save issues, with the exact same class name "Parent" at it also throws
Method [save] does not exist
The reason you can save the $parent model data is because of the name that you have given to the model as
Parent
Change the model name to something else and it will work as expected. Looks like the class Parent must be laravel's system class and we cannot give that name to our custom classes.
your Model is not set up correctly you find these in app/models/ there needs to be a Parent.php file that defines how laravel should use your information in the database. Eloquent Models - Laravel 4 Documentation
I have tested, this code is working properly. May be try composer update.
composer update

Combine all NotBlank error messages in Symfony2

I'm trying to combine all NotBlank error messages into one.
If the error array contains at least 1 error that is a NotBlank type, I want it to display only one message like "Please fill in all fields."
How can I do this?
Here's my twig code
{{form_start(form, {'attr': {'novalidate': 'novalidate'}})}}
<div>
{{form_widget(form.firstName)}}
{{form_widget(form.lastName)}}
</div>
<div>
{{form_widget(form.username)}}
{{form_widget(form.email)}}
</div>
<div>
{{form_widget(form.password.first, {'attr' : { 'placeholder' : 'Password' } })}}
{{form_widget(form.password.second, {'attr' : { 'placeholder' : 'Confirm Password' } })}}
</div>
<div>
{{form_label(form.birthday)}}
</div>
<div>
{{form_widget(form.birthday)}}
</div>
<div>
{{form_widget(form.gender)}}
</div>
<div>
{{form_widget(form.save)}}
</div>
{{ form_errors(form.firstName) }}
{{ form_errors(form.lastName) }}
{{ form_errors(form.username) }}
{{ form_errors(form.email) }}
{{ form_errors(form.password.first) }}
{{form_end(form)}}
You can create a CallbackValidator
http://symfony.com/doc/current/reference/constraints/Callback.html
and in the validate method, check if at least one of the desired fields is blank, and if true, call
/**
* #Assert\Callback
*/
public function validate(ExecutionContextInterface $context)
{
if(empty($this->field1) || empty($this->field2)) {
$context->addViolation($message);
}
}
This way you will receive a global form error.

Resources