Retrieve old value with validation for dynamic form in laravel - laravel-5

I have an issue.
I have dynamic form as per user wants.
Everything is going good except i cannot retrieve old values when validation occurs. What i want is validation message with old input values. The problem is due to dynamic form .
Here is my code :
<div class="col-sm-5">
<input class="form-control" type="text" name="key_name[]"
placeholder="Size" value="{{ old('key_name[]') }}">
</div>
<div class="col-sm-5">
<input class="form-control" type="text" name="key_value[]"
placeholder="Price" value="{{ old('key_value[]') }}">
</div>
<button type="button" class="btn btn-danger remove-field"><i
class="ion-trash-a"></i> Delete
</button>
#if ($errors->has('key_name[]'))
<div class="error-add-size-message">
<span class="help-block">
<strong> * {{ $errors->first('key_name[]') }}</strong>
</span>
</div>
#endif
Thanks in advance.

You can count form inputs in your controller and flash this count in the session.
$count = count($request->input("key_name"));
session()->flash("form_count",$count);

Related

Cannot find errors returned by validate method

I am using the validate method to validate user input and when I post a form with errors, I get redirected to the previous page but the form is not repopulated and the errors are not showing. I have include a partial view for showing errors in the page with the form. The partial view is:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
the action method in the controller is:
public function store(Request $request)
{
$request->validate([
'product_name' => 'required',
'age' => 'required',
'product_code' => 'required|alpha_num',
'price' => 'required|numeric',
]);
$product=new Product();
The view with the form is:
#section('content')
<div class="container">
#include('partials.errors')
<form action="/products/create" method="POST">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
#csrf
<div class="form-group">
<label>Product Name</label>
<input name="product_name" type="text" class="form-control">
</div>
<div class="form-group">
<label>Age</label>
<input name="age" type="text" class="form-control">
</div>
<div class="form-group">
<label>Gender</label>
<select class="form-control" name="gender">
<option>
Male
</option>
<option>
Female
</option>
Unisex
</option>
</select>
</div>
<div class="form-group">
<label>Product Code</label>
<input name="product_code" type="text" class="form-control">
</div>
<div class="form-group">
<label>Price</label>
<input name="price" type="text" class="form-control">
</div>
<div class="form-group">
<label>Product Category</label>
<select class="form-control" name="category_name">
#foreach ($product_categories as $product_category)
<option>{{ $product_category->category_name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Brand</label>
<select class="form-control" name="brand_name">
#foreach ($brands as $brand)
<option>{{ $brand->brand_name }}</option>
#endforeach
</select>
</div>
<button class="btn btn-primary" type="submit">Create</button>
</form>
</div>
#endsection
when I post a failed form, I get redirected to the view with the form but the form is not repopulated with the input that I entered. additionally, the erros are not shown but just an empty red div. According to a book I read, if the data isn’t valid, the validate method throws a ValidationException and the exception will return a redirect to the previous page, together with all of the user input and the validation errors. I am new to laravel.
You should use old() method to keep repopulate entered value in input field like below
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
To show validation error you have to add errors in each field for example like below
#error("product_code")
<div class="invalid-feedback">{{ $message }}</div>
#enderror
You can read more about old method here
https://laravel.com/docs/8.x/requests#retrieving-old-input
For validation error
https://laravel.com/docs/8.x/validation#the-at-error-directive
First, the CSRF token:
If you check the docs you'll see that you have 2 options how to add it:
#csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
You are doing both, remove one of them.
Second, the old input:
You are missing the old input call. For example:
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
Last, the errors:
You are doing it correctly.
If is still not working, check that your route is using the middleware web.

attributes in form that define in modal does not get dynamic value in laravel :(

I created a table for editing the Movie Object.
One of the table's column is a form that pops up with a modal class (bootstrap)
Here is my code:
<div class="modal-body">
<form method="post" action="{{asset(route('movies.update', $movie->id))}}">
<input type="hidden" name="_token" value="{{csrf_token()}}">
{{method_field('PATCH')}}
<div class="form-group">
<label for="movie-name" class="col-form-label">Name:</label>
<input type="text" class="form-control" name="movie_name" id="movie-name" placeholder="{{$movie->name}}">
</div>
<div class="form-group">
<label for="movie-director" class="col-form-label">Direcor:</label>
<select class="form-control" name="Director">
#foreach($directors as $director)
<option value="{{$director->id}}">{{$director->name}}</option>
#endforeach
</select>
</div>
<button class="form-control btn btn-success" type="submit" class="btn btn-primary">Send message</button>
</form></div>
When I choose one of the edit buttons, the value of the first item (movie) passes to my controller.
I've tested my code and find out it's happening because I have used the modal class.
Do you have any ideas to solve this problem?

Edit db record with modal window

I'm trying to edit some database record based on an ID that I'm saving into a button value.
#foreach ($employment as $empl)
<button data-toggle="modal" data-target="#edit-empl" href="#edit-empl" class="btn btn-default editbtn-modal" value="{{ $empl->id }}" type="button" name="editbtn">Edit</button>
<h3 class="profile-subtitle">{{ $empl->company }}</h3>
<p class="profile-text subtitle-desc">{{ $empl->parseDate($empl->from) }} - {{ $empl->parseDate($empl->to) }}</p>
#endforeach
As you can see here, I have an edit button with an id attached.
When I click edit I open a modal window to edit the fields and later on submit the form.
The thing is, I'm not sure how to get that id from the button into the modal window so I can compare the values and display the correct fields..
<form class="app-form" action="/profile/employment/edit/{id}" method="POST">
{{ csrf_field() }}
<input class="editID" type="hidden" name="editID" value="">
#foreach ($employment as $empl)
#if ($empl->id == buttonidhere)
<div class="form-group">
<label for="company">Company:</label>
<input type="text" name="company" value="{{ $empl->company }}">
</div>
<div class="form-group">
<label for="month">From:</label>
<input type="date" name="from" value="{{ $empl->from }}">
</div>
<div class="form-group">
<label for="to">To:</label>
<input type="date" name="to" value="{{ $empl->to }}">
</div>
#endif
#endforeach
<div class="row">
<div class="col-sm-6">
<input type="submit" class="btn btn-primary profile-form-btn" value="Save Changes">
</div>
</div>
</form>
I was able to pass the button value into the modal using javascript.. I put it into a hidden input but that doesn't help me at all because I can't get the input value in order to compare the values..
Solution 1: Using ajax
Step 1: Create a route in laravel which will return a JSON object containing employing data of requested employee.
For e.g,
/profile/employment/data/{empl_id}
Will get you employement data of id empl_id.
Step 2: Change your form as below
<form class="app-form" action="/profile/employment/edit/{id}" method="POST">
<input class="editID" type="hidden" name="editID" value="">
<div class="form-group">
<label for="company">Company:</label>
<input type="text" name="company" value="">
</div>
<div class="form-group">
<label for="month">From:</label>
<input type="date" name="from" value="">
</div>
<div class="form-group">
<label for="to">To:</label>
<input type="date" name="to" value="">
</div>
<div class="row">
<div class="col-sm-6">
<input type="submit" class="btn btn-primary profile-form-btn" value="Save Changes">
</div>
</div>
</form>
Step 3: Use javascript(jQuery) to get the data using ajax and load it into the form in modal.
jQuery code:
$(document).on("click", ".editbtn-modal", function() {
var id = $(this).val();
url = "/profile/employment/data/"+id;
$.ajax({
url: url,
method: "get"
}).done(function(response) {
//Setting input values
$("input[name='editID']").val(id);
$("input[name='company']").val(response.company);
$("input[name='to']").val(response.to);
$("input[name='from']").val(response.from);
//Setting submit url
$("modal-form").attr("action","/profile/employment/edit/"+id)
});
});
Solution 2: Using remote modal
Step 1:
Create another blade file for eg. editEmployee.blade.php and add the above form in it.
<form class="app-form" id="modal-form" action="/profile/employment/edit/{{ $empl->id }}" method="POST">
{{ csrf_field() }}
<input class="editID" type="hidden" name="editID" value="{{ $empl->id }}">
<div class="form-group">
<label for="company">Company:</label>
<input type="text" name="company" value="{{ $empl->company }}">
</div>
<div class="form-group">
<label for="month">From:</label>
<input type="date" name="from" value="{{ $empl->from }}">
</div>
<div class="form-group">
<label for="to">To:</label>
<input type="date" name="to" value="{{ $empl->to }}">
</div>
<div class="row">
<div class="col-sm-6">
<input type="submit" class="btn btn-primary profile-form-btn" value="Save Changes">
</div>
</div>
</form>
Step 2: Create a controller which would return the above form as HTML.
Tip: use render() function. example
Step 3: load the form into modal window before showing using javascript(jQuery)
considering your modal id is "emp-modal"
$(document).on("click", ".editbtn-modal", function() {
var id = $(this).val();
url = "/profile/employment/data/"+id;
$('#emp-modal').modal('show').find('.modal-body').load(url);
});
One solution would be to send the details you want the same way you send the id to the modal.
and the proper way to send variables to modal is to include this in the button that opens modal:
data-variablename="{{$your-variable}}"
use this jQuery to get the values of your variables to modal. where edit-empl is the id of your modal and data-target of your button
$('#edit-empl').on('show.bs.modal',function (e) {
var variablename= $(e.relatedTarget).data('variablename');
$(e.currentTarget).find('input[id="yourinputID"]').val(variablename);

Laravel 5.3 - TokenMismatchException on every post request

I was working on my project normally and when i hit refresh to see a change that i just made in one of the html pages, the page showed a text on top left "Redirecting to: http://localhost:8888/xxx ". It redirected me to the login page. When i clicked login, the 'TokenMismatchException' error showed:
The login form has the hidden input _token , header has it too. As i said everything was fine. I have been working on this project for 2 months. Is this related to files permissions ?
Here is the login form.
<form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-7">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-7">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ url('/password/reset') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
Thanks :)
After i installed a fresh laravel copy i started to paste my old files to see where would regenerate the mismatch token problem.
It went down to the routes/web.php file. Something there was causing the error. It was a space before the opening tag of php on routes/web.php file.
Something that did not caught my eye. Like that the project was working fine but suddenly did not anymore.
As i read , the space is considered an output. Check this explanation :
https://stackoverflow.com/a/4345822/6634389
Why don't you use {{ csrf_field() }} or try with that?
Run:
php artisan cache:clear; composer dump-autoload; composer clear-cache
Refresh the browser, make sure you generated the key for your app. This should work. For me it did.
You are refreshing your page, so each time the pages load with same csrf-token. So when you are trying to post your data, laravel refuses it and provide error message due to each request should have a unique csrf-token. You can read about this herelaravekl csrf protection
Either you should again reload your page or you should disable the csrf protection by commenting it inside the
App=>Http=>Kernel.php
inside the $middlewareGroups=>'web'
\App\Http\Middleware\VerifyCsrfToken::class, //comment this line
I was having the same issue, I solved it by using following in my view
<input type="hidden" name="_token" value="{{ session()->getToken() }}">

Laravel Edit Post Content using CKeditor

I am trying to edit existing post using CKeditor. Content isn't loading.
<div class="form-group">
<label>Content</label>
<textarea id="editor1" name="content" class="form-control" rows="3" placeholder="Enter ...">
{{ Request::old('content') }}
</textarea>
</div>
Also im having trouble getting date from the database too.
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" name="published_at" class="form-control" value="{{ $post->published_at->format('M jS Y') }}">
</div>
For the textarea, check for old input, but fall back to defaulting to using the model's content attribute (the post's content)
<textarea ....>{!! Request::old('content', $post->content) !!}</textarea>
For your date issue, I don't know what problem you are having.

Resources