How to handle laravel fields error according to data tables editor plugin create edit
Before going to explain lets assume we want to create category and for time being we have one field that is name.
And already we have controller,model and route established.
For laravel field errors to be compatible with datatables editor we need to do following.
Create form request for validation of category creation as below:
File location: app / Http / Requests /
File name: AddCategoryFormRequest.php
File contents:
File location: app / Http / Requests /
File name: CustomFormRequest.php
File contents:
File location: app / Http / Requests /
File name: AddCategoryFormRequest.php
File contents:
namespace App\Http\Requests;
use App\Http\Requests\CustomFormRequest;
class AddCategoryFormRequest extends CustomFormRequest {
public function rules() {
return [
'name' => 'required|max:255',
];
}
}
And category datatables and editor configuration as below:
var create = new $.fn.dataTable.Editor({
ajax: {url: 'url here',type:'POST'},
table: '#categories-table',
"idSrc": "id",
fields: [{name: "name" , data: "name", label: "cat name"}]
});
$('#categories-table').DataTable({
dom: "Bfrtip",
responsive: true,
"aoColumnDefs": [
],
processing: true,
serverSide: true,
ajax: {url: 'url here',type:'POST'},
columns: [{name: "name" , data: "name", label: "cat name"}],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [{
extend: "create",
editor: create
}],
"order": [[ 1, "asc" ]]
});
Have you seen that AddCategoryFormRequest extends CustomFormRequest instead of Request class??
Here is a trick to handle fields error and return as errors as datatables editor expects. Full class definition is given below:
File location: app / Http / Requests /
File name: CustomFormRequest.php
File contents:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\Validation\Validator;
class CustomFormRequest extends FormRequest {
/**
* Get the validator instance for the request.
*
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function getValidatorInstance() {
$factory = $this->container->make('Illuminate\Validation\Factory');
$data = $this->all()['data'];
foreach ($data as $k => $d) {
$this->id=$k;
return $factory->make(
$d, $this->container->call([$this, 'rules']), $this->messages(), $this->attributes()
);
}
}
public function authorize() {
// Only allow logged in users
// return \Auth::check();
// Allows all users in
return true;
}
// OPTIONAL OVERRIDE
public function forbiddenResponse() {
// Optionally, send a custom response on authorize failure
// (default is to just redirect to initial page with errors)
//
// Can return a response, a view, a redirect, or whatever else
return Response::make('Permission denied!', 403);
}
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return \Symfony\Component\HttpFoundation\Response
*/
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson()) {
return new JsonResponse($errors);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
/**
* Format the errors from the given Validator instance.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return array
*/
protected function formatErrors(Validator $validator)
{
$fieldErrors = [];
foreach ($validator->errors()->getMessages() as $key => $message) {
$fieldErrors[] = ['name' => $key, 'status' => $message];
}
return ['fieldErrors' => $fieldErrors];
}
}
Now you should think about laravel controller which will handle request for creating category item
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Inventory\Category as model;
use App\Http\Requests\AddCategoryFormRequest as AddFormRequest;
class CategoryController extends Controller {
protected $config = [];
public function __construct() {
}
public function add(AddFormRequest $request) {
$data = $request->get('data');
$fields = ["name"];//just to care which field can be populated while creation
$response = [];
$response['data'] = [];
foreach ($data as $id => $d) {
$model = new model;
foreach ($fields as $field) {
if (isset($d[$field])) {
$model->$field = $d[$field];
}
}
if ($model->save()) {
$response['data'][] = $model;
} else {
$response['error'] = 'Error';
}
}
return $response;
}
}
Now its completed and you can run add feature of datatables editor plugin with using datatables for tables rendering.
Feedback is always welcome.
Comments
Post a Comment