dependent and conditional validations not working - php

Hi all am trying to do validations for a text field which is depends on other selected value .there is two columns buyer and reference number.so the validation is when i select particular names in buyer column then the reference must be required.
Below is my code
model::
public static $rules = array(
'delivery_contact_no' => 'required|numeric',
'external_ref_number' => 'required',
);
controller::
$check = false;
if ($_POST["user"] == '11Street') {
$check = true;
if (Input::get('external_ref_number') == "") {
$rules = array(
'external_ref_number' => 'required'
);
$messages = array(
'external_ref_number.required' => 'The External Reference Number Must be required ',
);
}
if ($check) {
$validator = Validator::make(Input::all(), $message);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
}
}
I am inserting input data like below:
$get = array(
'user' => trim($_POST["user"]),
'external_ref_number' => trim(Input::get('external_ref_number')),
);
so the validation is when I select particular names in buyer column then the reference must be required. below is view code
view::
<div class="form-group #if ($errors->has('user')) has-error #endif">
{{ Form::label('user', 'Buyer *', array('class'=> 'col-lg-2 control-label')) }}
<div class="col-lg-4">
{{ Form::text('user', Input::old('user'), array('class'=> 'form-control', 'autofocus' => 'autofocus', 'readonly' => 'readonly')) }}
{{ $errors->first('user', '<p class="help-block">:message</p>') }}
<input type="hidden" id="user_id" name="user_id">
</div>
<div class="col-xs-1">
<div class="input-group">
<div class="input-group-btn">
<span class="pull-left"><button id="selectUserBtn" class="btn btn-primary selectUserBtn" href="/transaction/ajaxcustomer"><i class="fa fa-plus"></i> Select Buyer</span>
</div>
</div>
</div>
</div>
<div class="form-group required {{ $errors->first('external_ref_number', 'has-error') }}">
{{ Form::label('external_ref_number', 'External reference number ', array('class' => 'col-lg-2 control-label')) }}
<div class="col-lg-4">
{{ Form::text('external_ref_number', $orderMappedInfo['external_ref_number'], ['placeholder' => 'External reference number', 'class' => 'form-control']) }}
{{ $errors->first('external_ref_number', '<p class="help-block">:message</p>') }}
</div>
</div>
The validation code which I wrote is not working. Please help me to solve this issue.
I am trying to do validations for a text field which is depends on other selected value.
There are two columns buyer and reference number.
so the validation is when i select particular names in buyer column then the reference must be required.

Related

Get old or user variable value on form after custom request validation error, view with two different forms

EDIT:
Your solutions are working for text inputs and textareas, but checkboxes are not working correctly for me.
This was my original checkbox:
{{ Form::checkbox('active', true, (isset($user->active)) ? old($user->active) : true, ['class' => 'custom-control-input', 'id' => 'active']) }}
I've tried a lot of possible solutions like adding old('active', isset($user) ? $user->active: true) instead, but when an error occurs I lose the values from this input. On the controller I was checking this, but if I change the input to the 'new solution' active is always false on my db:
if(!array_key_exists('active', $validated)){
$validated = array_add($validated, 'active', '0');
}
ORIGINAL QUESTION (PARTIALLY RESOLVED):
I have one blade view call edit with two forms, but each one is calling his own method/route. One form is for edit/store the user and the other is a form in a modal to change the user password. When I change the password and no validation error happens, the other form still has all of his values that is getting from old() or $user variable via index method. But if for example the passwords do not match, a validation error occurs, and the values from the edit/store user form disappear.
Forms are pretty simple (remember, they are on the same view, and the one that is giving me problems is the edit/create one), and each one call a different method from UserController
Form 1 for edit users (simplified)
#if($user->exists)
{{ Form::model($user, ['route' => ['users.update', $user], 'class' => 'needs-validation', 'novalidate'=>'']) }}
#method('PATCH')
#else
{{ Form::model($user, ['route' => ['users.store'], 'class' => 'needs-validation', 'novalidate'=>'']) }}
#method('POST')
#endif
#csrf
<div class="form-group">
<div class="row">
<div class="col-sm-4">
{{ Form::label('cif', __('users.cif'), ['class' => 'form-label']) }}
{{ Form::text('cif', (isset($user->cif)) ? old($user->cif) : '', ['class' => 'form-control', 'required','maxlength'=>'12', 'minlength'=>'9']) }}
{{ Form::hidden('validate','', ['class' => 'form-control', 'required', 'id'=>'validate']) }}
</div>
<div class="col-sm-6">
{{ Form::label('name', __('users.name'), ['class' => 'form-label']) }}
{{ Form::text('name', (isset($user->name)) ? old($user->name) : '', ['class' => 'form-control','required','maxlength'=>'255']) }}
</div>
<div class="col-sm-2">
{{ Form::label('initials', __('users.initials'), ['class' => 'form-label']) }}
{{ Form::text('initials', (isset($user->initials)) ? old($user->initials) : '', ['class' => 'form-control', 'required','maxlength'=>'5']) }}
</div>
</div>
<div class="col-sm-6">
{{ Form::label('province', __('users.province'), ['class' => 'form-label']) }}
{{ Form::text('province', (isset($user->city)) ? $user->city->province->name : '', ['class' => 'form-control', 'disabled'=>'']) }}
</div>
{!! Form::close() !!}
Form 2: Update password
<form id="change-password" action="{{route('users.change.password', $user)}}" method="POST">
#csrf
<div class="modal-body">
<div class="card-body">
<div class="panel-tag">
<p>Las contraseñas debe de coincidir y tener más de 8 carácteres</p>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Contraseña</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password" minlength="8">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirmation" class="col-md-4 col-form-label text-md-right">Confirmar contraseña</label>
<div class="col-md-6">
<input id="password-confirmation" type="password" class="form-control #error('password') is-invalid #enderror" name="password_confirmation" required autocomplete="new-password" minlength="8">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="change" type="submit" form="change-password" class="btn btn-primary">Confirmar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
</div>
</form>
UserController I'm going to paste two methods, one for store/user, the other for change the password. Update method is very similar.
public function store(StoreUserRequest $request)
{
if( $request['validate'] == 1 ){
$validated = $request->validated();
$validated['password'] = Hash::make($validated['password']);
$id = DB::table('users')->insertGetId($validated);
return redirect()->route('users.edit',['user'=>$id])->with('status', 'created');
} else {
return redirect()->back()->withInput()->with('status', 'error_dni');
}
}
public function changePassword(PasswordUserRequest $request, User $user)
{ // HERE IS WHERE I THINK IS THE PROBLEM, IF VALIDATION FAILS (FOR EXAMPLE PASSWORD CONFIRM) VALUES FROM THE OTHER FORM DISAPPEAR AND IT DOESNT GET INTO THIS METHOD
$pass = Hash::make($request->password);
$user->password = $pass;
$action = $user->save();
if ($action) {
return redirect()->back()->with('status', 'change_password_ok');
}
return redirect()->back()->with('status', 'error_change_password');
}
PasswordUserRequest This is the request to validate the password form
public function rules()
{
return [
'password' => 'required|string|confirmed';
];
}
The route would be something like:
users/{user}/edit
I've spent all day trying to fix this and still didn't found a solution. My english is not very good so please tell me if I'm not explaining something correctly and I will edit the question.
Thanks and hope that I can find a solution.
old values are from input name
<input type="text" name="input" value="{{old('input')}}"
example
<div class="col-sm-4">
{{ Form::label('cif', __('users.cif'), ['class' => 'form-label']) }}
{{ Form::text('cif', old('cif', $user->cif ?? ''), ['class' => 'form-control', 'required','maxlength'=>'12', 'minlength'=>'9']) }}
{{ Form::hidden('validate','', ['class' => 'form-control', 'required', 'id'=>'validate']) }}
</div>
//$user->cif ?? '' <- left or right hand-side operand, return right-hand if left is null or undefined
//old('input', $user->cif ?? '') <- if old input available, use old input, if not, $user will be displayed
form::checkbox:
First argument : name
Second argument : value
Third argument : checked or not checked (true or false)
Fourth argument : additional attributes
note that value is attribute(value) and checked is attribute(checked)
then
{{ Form::checkbox('active', true, (isset($user->active)) ? $user->active : true, ['class' => 'custom-control-input', 'id' => 'active']) }}
//2nd parameter (true) will always set checkbox value to 1(true)
//(isset($user->active)) ? $user->active : true <- will set default to true (checked) if $user is null or undefined
//maybe try
{{ Form::checkbox('active', $user->active ?? false, $user->active ?? false) }}
//if $user != null, put $user->active else put false
//if $user != null, set checked value based on $user->active else put false
in html looks like this
<input type="checkbox" value="1" checked="checked">
then you need to add inline event onchange="$(this).is(':checked') ? $(this).val(1) : $(this).val(0);" in the 4th parameter of form::checkbox to change the default on runtime
If I understood all correctly, you should do this way:
old('name', isset($user) ? $user->name : ''),
Here you trying to get old name input, and if it doesn't exist, in second parameter od old function you are getting default value, which is user's name in case of user exists
There is documentation, which can help you to understand much more.

Saving data into database using a form with multiple pages and one to many relationship laravel

I have 2 form blade.php to get data and save into database. But I am doing a one to many relationship where there is one bear and many fish
But I don't know how to do it properly, previously I used this:
$bear = Bear::create(['Name' => $request->input('name_of_bear')]);
$bear->fishes()->create(['type_of_fish' => $fishType);
But it is only for 1 page, but what if I have 2 page, what do I need to do? Do I use associate, flash, session or something else to save the data into the database?
If possible can I also have some example for reference. Thank you
page1.blade.php:
{!! Form::open(['url' => 'page1/submit']) !!}
<div class="form-group">
{{Form::label('Name', 'Name of Bear ')}}
{{Form::text('Name', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('bear_type', 'Type of Bear ')}}
{{Form::text('bear_type', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::submit('Next', ['class' => 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
Controller for page1:
public function submit(Request $request)
{
$data = array();
$data['Name'] = $request->Name;
$data['bear_type'] = $request->bear_type;
$BearDetails = bear::create($data);
return redirect('http://test.dev/page2');
}
page2.blade.php
{!! Form::open(['url' => 'page2/submit']) !!}
<div class="form-group">
{{ Form::label('type_of_fish','Type of fish bear eat')}}
<input type="checkbox" id="inlineCheckbox1" name="type_of_fish[]" value="Salmon"> Salmon
<input type="checkbox" id="inlineCheckbox2" name="type_of_fish[]" value="Sardine"> Sardine
</div>
{{ Form::label('fish_location','Where is the fish located near at?')}}
<input type="checkbox" id="inlineCheckbox1" name="fish_location[]" value="Canyon"> Canyon
<input type="checkbox" id="inlineCheckbox2" name="fish_location[]" value="Rainforest"> Rainforest
</div>
{!! Form::close() !!}
</div>
<div class="form-group">
{{Form::submit('Submit', ['class' => 'btn btn-primary'])}}
</div>
Controller for page2:
$test = array();
$test['fish_location'] = $request->fish_location;
$test['type_of_fish'] = $request->type_of_fish;
$bear = bear::create($data);
$fish = fish::create($test);
$fish->user_particular()->associate($bear);
$fish->save();
return ('thank you');
}
bear model:
class bear extends Eloquent
{
protected $primaryKey = 'id';
public function fishs() {
return $this->hasMany('App\fish,'bear_id');
}
}
fish model:
class fish extends Eloquent
{
protected $fillable = array('name', 'bear_id');
// DEFINE RELATIONSHIPS
public function bears() {
return $this->belongsTo('App\bear);
}
}

How to put input textarea in an array? (Laravel 5.3)

My view blade is like this :
#foreach($reviews as $key => $review)
...
<div class="form-group">
{!! Form::open(['route' => 'message.review.update', 'method' => 'post', 'id' => 'reviewform']) !!}
<label for="review" class="sr-only">Review</label>
{!! Form::textarea('review', null, ['class' => 'form-control', 'id' => 'review', 'rows'=>3,'required'=>'required']) !!}
#if ($errors->has('review'))
<span class="help-block">
<strong>{{ $errors->first('review') }}</strong>
</span>
#endif
{!! Form::hidden('id', $review->_id) !!}
{!! Form::hidden('store', $review->store_id) !!}
{!! Form::close() !!}
</div>
...
#endforeach
My routes is like this :
Route::group(['prefix' => 'message','as'=>'message.'],function(){
Route::post('review/update', ['as'=>'review.update','uses'=>'ReviewController#update']);
});
My controller to update is like this :
public function update(CreateReviewRequest $request)
{
$param = $request->only('id', 'review', 'store');
...
}
Before update, it will call CreateReviewRequest to validation
My CreateReviewRequest is like this :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateReviewRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'review'=>'required|max:300'
];
}
}
When, only one data, I input comment and submit, it works
But, when more than one data, it does not works
There exist error like this :
An invalid form control with name='review' is not focusable.
How can I solve it?
You made some mistakes here... In HTML IDs MUST be unique. You can't put "review" as id for all your textareas... My comment was about to use an array as name like this name=review[], and in the ID add dynamically the $key at the end of the id to make them unique.
This will give you something like this :
<textarea name="review[]" class="form-control" id="review0" rows="3" required></textarea>
<textarea name="review[]" class="form-control" id="review1" rows="3" required></textarea>
<textarea name="review[]" class="form-control" id="review2" rows="3" required></textarea>
EDIT
I've just founded this stackoverflow topic. Could you try to add novalidate attribute in the <form>?
<form name="myform" novalidate>
Something like this in your case :
{!! Form::open(['route' => 'message.review.update', 'method' => 'post', 'id' => 'reviewform', 'novalidate']) !!}
VIEW
{!! Form::textarea('review[]', null, ['class' => 'form-control', 'id' => 'review', 'rows'=>3,'required'=>'required']) !!}
or
<textarea name="review[]" class="form-control" id="review" rows="3" required></textarea>
You must insert name field like array empty, when you will submit the form you can get all values in your controller calling:
CONTROLLER
public function update(Request $request)
{
// Validate the form
$this->validate($request, [
'review' => 'required',
]);
// get inputs
$review_input = $request->get('review');
dd($review_input); // see if it work
}

Laravel 5.2 two forms in different pages but same method and controller

I am using Laravel 5.2 and I have two forms in different pages but same method and controller..
Both use public function store(Request $request){} method.
First Form in 'show.blade.php' page:
<form action="{{ url('projects') }}" name="comment_form" class="row" method="POST">
{{ csrf_field() }}
<div class="col-md-3">
<input placeholder="Name" name="name" type="text">
</div>
<div class="col-md-3">
<input placeholder="Email" name="email" type="text">
</div>
<div class="col-md-3">
<input placeholder="Subject" name="subject" type="text">
</div>
<div class="col-md-3">
<input value="Id Number : {{ $project -> id }}" name="project_id" type="text" readonly>
</div>
<div class="col-md-12">
<textarea placeholder="Comments" name="comments" cols="10" rows="10"></textarea>
</div>
<div class="col-md-12">
<input type="submit" value="Send Comments">
</div>
</form>
Second Form in 'create.blade.php' page:
{!! Form::open(array('route' => 'projects.store', 'files' => true, 'name' => 'project_form')) !!}
{{ Form::label('title', 'Title:', ['class' => 'top-bottom-margin']) }}
{{ Form::text('title', null, ['class' => 'form-control', 'maxlength' => '255']) }}
{{ Form::label('image', 'Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('image', ['accept' => 'image/*']) }}
{{ Form::label('second_image', 'Optional Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('second_image', ['accept' => 'image/*']) }}
{{ Form::label('third_image', 'Optional Image: ', ['class' => 'top-bottom-margin']) }}
{{ Form::file('third_image', ['accept' => 'image/*']) }}
{{ Form::label('body', 'Body:', ['class' => 'top-bottom-margin']) }}
{{ Form::textarea('body', null, ['class' => 'form-control']) }}
{{ Form::submit('Create Project', ['class' => 'btn btn-success btn-lg btn-block top-bottom-margin']) }}
{!! Form::close() !!}
ProjectsController.php method code:
public function store(Request $request)
{
$data = $request->all();
if(isset($data['project_form'])){
// validation START
$this -> validate($request, array(
'title' => 'required | max:255',
'body' => 'required',
'image' => 'required'
));
// validation END
// storing in database
$project = new Project;
$project -> title = $request -> title;
$project -> body = $request -> body;
// First images START
$image = $request -> file('image');
$fileName = time() . '.' . $image -> getClientOriginalExtension();
$location = public_path('admin_images/' . $fileName);
Image::make($image) -> resize(860, 600) -> save($location);
//database store
$project -> image = $fileName;
//First images END
if ($request->hasFile('second_image')){
// second images START
$rand_number = rand(100, 2000);
$second_image = $request -> file('second_image');
$secondFileName = time() . $rand_number . '.' . $second_image -> getClientOriginalExtension();
$secondLocation = public_path('admin_images/' . $secondFileName);
Image::make($second_image) -> resize(860, 600) -> save($secondLocation);
//database store
$project -> second_image = $secondFileName;
// second images END
}
if ($request->hasFile('third_image')){
// third images START
$second_rand_number = rand(3000, 5000);
$third_image = $request -> file('third_image');
$thirdFileName = time() . $second_rand_number . '.' . $third_image -> getClientOriginalExtension();
$thirdLocation = public_path('admin_images/' . $thirdFileName);
Image::make($third_image) -> resize(860, 600) -> save($thirdLocation);
//database store
$project -> third_image = $thirdFileName;
// third images END
}
$project -> save();
Session::flash('success', 'Your project was created successfully!');
return redirect() -> route('projects.show', $project -> id);
}
Now I check if the comment_form is submitted or the project_form is submitted?
You can create hidden element to pass variable:
{!! Form::hidden('from', 'someView') !!}
And then get it in controller:
if ($request->from == 'someView') {
....
Also, you could pass variable by using sessions and by retrieving previous page URL, but I think hidden form element is the best choice when you're using form.
You could put a name and value to the submit button and check that.
if ($request->get('submit') == 'project') {
// do something
} elseif ($request->get('submit') == 'comment') {
// do something else
}
or use a switch
switch ($request->get('submit')) {
case 'project':
// do something
break;
case 'comment':
// do something else
break;
default:
// do this if above does not apply
break;
}

Laravel Form Questions

Two problems with using the Form class in laravel. Finding it hard to get used to the parameter passing with arrays I am using twitter bootstrap:
Adding a class to a select type does not work?
Using radio buttons to output properly
1
{{ Form::select('title', array('Mr', 'Mrs', 'Ms', 'Miss', 'Master', 'Dr', 'Prof'), array('class' => 'input-small')) }}
2
<div class="control-group">
<div class="controls">
{{ Form::label('gender', 'Gender', array('class' => 'control-label')) }}
<label class="radio">
{{ Form::radio('gender', 'Male') }} Male
</label>
<label class="radio">
{{ Form::radio('gender', 'Female') }} Female
</label>
<p class="help-block"> Please enter your gender</p>
</div>
</div>
1) You are passing the wrong values
public static function select($name, $options = array(), $selected = null, $attributes = array())
You must pass the selected value, session or Input::old('name')
{{ Form::select('title', array('Mr', 'Mrs', 'Ms', 'Miss', 'Master', 'Dr', 'Prof'), $selected = NULL, array('class' => 'input-small')) }}
2) Looks fine on my templates, I have the same code. Can you post more info?

Categories