Initial commit for rider crud

This commit is contained in:
Ramon Gutierrez 2018-01-16 06:06:52 +08:00
parent 7739b23a7d
commit 278a37bc53
4 changed files with 722 additions and 0 deletions

34
config/routes/rider.yaml Normal file
View file

@ -0,0 +1,34 @@
rider_list:
path: /riders
controller: App\Controller\RiderController::index
rider_rows:
path: /riders/rows
controller: App\Controller\RiderController::rows
methods: [POST]
rider_create:
path: /riders/create
controller: App\Controller\RiderController::addForm
methods: [GET]
rider_create_submit:
path: /riders/create
controller: App\Controller\RiderController::addSubmit
methods: [POST]
rider_update:
path: /riders/{id}
controller: App\Controller\RiderController::updateForm
methods: [GET]
rider_update_submit:
path: /riders/{id}
controller: App\Controller\RiderController::updateSubmit
methods: [POST]
rider_delete:
path: /riders/{id}
controller: App\Controller\RiderController::destroy
methods: [DELETE]

View file

@ -0,0 +1,365 @@
<?php
namespace App\Controller;
use App\Ramcar\BaseController;
use App\Entity\Rider;
use App\Entity\Hub;
use Doctrine\ORM\Query;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class RiderController extends BaseController
{
public function index()
{
$this->denyAccessUnlessGranted('rider.list', null, 'No access.');
$params = $this->initParameters('rider_list');
return $this->render('rider/list.html.twig', $params);
}
public function rows(Request $req)
{
$this->denyAccessUnlessGranted('rider.list', null, 'No access.');
// get query builder
$qb = $this->getDoctrine()
->getRepository(Rider::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)')
->join('q.hub', 'hub');
// add filters to count query
$this->setQueryFilters($datatable, $tquery);
$total = $tquery->getQuery()
->getSingleScalarResult();
// get current page number
$page = $datatable['pagination']['page'] ?? 1;
$perpage = $datatable['pagination']['perpage'];
$offset = ($page - 1) * $perpage;
// add metadata
$meta = [
'page' => $page,
'perpage' => $perpage,
'pages' => ceil($total / $perpage),
'total' => $total,
'sort' => 'asc',
'field' => 'id'
];
// build query
$query = $qb->select('q')
->addSelect('hub.name as hub_name');
// add filters to query
$this->setQueryFilters($datatable, $query);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy('q.' . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
// Query::HYDRATE_ARRAY);
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['first_name'] = $orow->getFirstName();
$row['last_name'] = $orow->getLastName();
$row['contact_num'] = $orow->getContactNumber();
$row['hub'] = $orow['hub_name'];
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// check if they have access to super admin users
if (!$this->isGranted('rider.role.sadmin') && $orow->isSuperAdmin())
{
$rows[] = $row;
continue;
}
// add crud urls
if ($this->isGranted('rider.update'))
$row['meta']['update_url'] = $this->generateUrl('rider_update', ['id' => $row['id']]);
if ($this->isGranted('rider.delete'))
$row['meta']['delete_url'] = $this->generateUrl('rider_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
public function addForm()
{
$this->denyAccessUnlessGranted('rider.add', null, 'No access.');
$params = $this->initParameters('rider_list');
$params['obj'] = new Rider();
$params['mode'] = 'create';
$em = $this->getDoctrine()->getManager();
// get parent associations
$params['hubs'] = $em->getRepository(Hub::class)->findAll();
// response
return $this->render('rider/form.html.twig', $params);
}
public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('rider.add', null, 'No access.');
// create new row
$em = $this->getDoctrine()->getManager();
$row = new Rider();
// set and save values
$row->setRidername($req->request->get('username'))
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setEmail($req->request->get('email'))
->setContactNumber($req->request->get('contact_no'))
->setEnabled($req->request->get('enabled') ? true : false)
->clearRoles();
// set roles
$roles = $req->request->get('roles');
if (!empty($roles)) {
foreach ($roles as $role_id) {
// check if role exists
$role = $em->getRepository(Role::class)->find($role_id);
if (!empty($role))
{
// check access to super user roles
if ($role->isSuperAdmin() && !$this->isGranted('rider.role.sadmin'))
continue;
$row->addRole($role);
}
}
}
// validate
$errors = $validator->validate($row);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// get password inputs
$password = $req->request->get('password');
$confirm_password = $req->request->get('confirm_password');
// custom validation for password fields
if (!$password) {
$error_array['password'] = 'This value should not be blank.';
} else if ($password != $confirm_password) {
$error_array['confirm_password'] = 'Passwords do not match.';
} else {
// encode password
$enc = $ef->getEncoder($row);
$encoded_password = $enc->encodePassword($req->request->get('password'), $row->getSalt());
// set password
$row->setPassword($encoded_password);
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
} else {
// validated! save the entity
$em->persist($row);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
}
public function updateForm($id)
{
$this->denyAccessUnlessGranted('rider.update', null, 'No access.');
$params = $this->initParameters('rider_list');
$params['mode'] = 'update';
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(Rider::class)->find($id);
// make sure this row exists
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
// get roles
$em = $this->getDoctrine()->getManager();
$params['roles'] = $em->getRepository(Role::class)->findAll();
$params['obj'] = $row;
$params['values'] = [];
// response
return $this->render('rider/form.html.twig', $params);
}
public function updateSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('rider.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(Rider::class)->find($id);
// make sure this row exists
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
// set and save values
$row->setRidername($req->request->get('username'))
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setEmail($req->request->get('email'))
->setContactNumber($req->request->get('contact_no'))
->setEnabled($req->request->get('enabled') ? true : false)
->clearRoles();
// set roles
$roles = $req->request->get('roles');
if (!empty($roles)) {
foreach ($roles as $role_id) {
// check if role exists
$role = $em->getRepository(Role::class)->find($role_id);
if (!empty($role))
$row->addRole($role);
}
}
// validate
$errors = $validator->validate($row);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// get password inputs
$password = $req->request->get('password');
$confirm_password = $req->request->get('confirm_password');
// custom validation for password fields
if ($password || $confirm_password) {
if ($password != $confirm_password) {
$error_array['confirm_password'] = 'Passwords do not match.';
} else {
// encode password
$enc = $ef->getEncoder($row);
$encoded_password = $enc->encodePassword($req->request->get('password'), $row->getSalt());
// set password
$row->setPassword($encoded_password);
}
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
} else {
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
}
public function destroy($id)
{
$this->denyAccessUnlessGranted('rider.delete', null, 'No access.');
$params = $this->initParameters('rider_list');
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(Rider::class)->find($id);
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
// delete this row
$em->remove($row);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
// check if datatable filter is present and append to query
protected function setQueryFilters($datatable, &$query) {
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('hub.name LIKE :filter')
->orWhere('q.first_name LIKE :filter')
->orWhere('q.last_name LIKE :filter')
->orWhere('q.contact_num LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -0,0 +1,162 @@
{% extends 'base.html.twig' %}
{% block body %}
<!-- BEGIN: Subheader -->
<div class="m-subheader">
<div class="d-flex align-items-center">
<div class="mr-auto">
<h3 class="m-subheader__title">Riders</h3>
</div>
</div>
</div>
<!-- END: Subheader -->
<div class="m-content">
<!--Begin::Section-->
<div class="row">
<div class="col-xl-8 offset-xl-2">
<div class="m-portlet m-portlet--mobile">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon">
<i class="la la-user"></i>
</span>
<h3 class="m-portlet__head-text">
{% if mode == 'update' %}
Edit Rider
<small>{{ obj.getRidername() }}</small>
{% else %}
New Rider
{% endif %}
</h3>
</div>
</div>
</div>
<form id="row-form" class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" method="post" action="{{ mode == 'update' ? url('rider_update_submit', {'id': obj.getId()}) : url('rider_create_submit') }}">
<div class="m-portlet__body">
<div class="form-group m-form__group row no-border">
<label class="col-lg-2 col-form-label" data-field="first_name">
First Name:
</label>
<div class="col-lg-4">
<input type="text" name="first_name" class="form-control m-input" value="{{ obj.getFirstName() }}">
<div class="form-control-feedback hide" data-field="first_name"></div>
</div>
<label class="col-lg-2 col-form-label" data-field="last_name">
Last Name:
</label>
<div class="col-lg-4">
<input type="text" name="last_name" class="form-control m-input" value="{{ obj.getLastName() }}">
<div class="form-control-feedback hide" data-field="last_name"></div>
</div>
</div>
<div class="form-group m-form__group row">
<label class="col-lg-2 col-form-label" data-field="contact_no">
Contact Number:
</label>
<div class="col-lg-4">
<input type="text" name="contact_no" class="form-control m-input" value="{{ obj.getContactNumber() }}">
<div class="form-control-feedback hide" data-field="contact_no"></div>
</div>
<label class="col-lg-2 col-form-label" data-field="hub">
Hub:
</label>
<div class="col-lg-4">
<select class="form-control m-input" id="hub" name="hub">
<option value=""></option>
{% for hub in hubs %}
<option value="{{ hub.getID() }}"{{ obj.getHub() and hub.getID() == obj.getHub().getID() ? ' selected' }}>{{ hub.getName() }}</option>
{% endfor %}
</select>
<div class="form-control-feedback hide" data-field="hub"></div>
</div>
</div>
<div class="form-group m-form__group row">
</div>
</div>
<div class="m-portlet__foot m-portlet__foot--fit">
<div class="m-form__actions m-form__actions--solid m-form__actions--right">
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-success">Submit</button>
<a href="{{ url('rider_list') }}" class="btn btn-secondary">Cancel</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
$(function() {
$("#row-form").submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
method: "POST",
url: form.prop('action'),
data: form.serialize()
}).done(function(response) {
// remove all error classes
removeErrors();
swal({
title: 'Done!',
text: 'Your changes have been saved!',
type: 'success',
onClose: function() {
window.location.href = "{{ url('rider_list') }}";
}
});
}).fail(function(response) {
var errors = response.responseJSON.errors;
var firstfield = false;
// remove all error classes first
removeErrors();
// display errors contextually
$.each(errors, function(field, msg) {
var formfield = $("[name='" + field + "']");
var label = $("label[data-field='" + field + "']");
var msgbox = $(".form-control-feedback[data-field='" + field + "']");
// add error classes to bad fields
formfield.addClass('form-control-danger');
label.addClass('has-danger');
msgbox.html(msg).addClass('has-danger').removeClass('hide');
// check if this field comes first in DOM
var domfield = formfield.get(0);
if (!firstfield || (firstfield && firstfield.compareDocumentPosition(domfield) === 2)) {
firstfield = domfield;
}
});
// focus on first bad field
firstfield.focus();
// scroll to above that field to make it visible
$('html, body').animate({
scrollTop: $(firstfield).offset().top - 200
}, 100);
});
});
// remove all error classes
function removeErrors() {
$(".form-control-danger").removeClass('form-control-danger');
$("[data-field]").removeClass('has-danger');
$(".form-control-feedback[data-field]").addClass('hide');
}
});
</script>
{% endblock %}

View file

@ -0,0 +1,161 @@
{% extends 'base.html.twig' %}
{% block body %}
<!-- BEGIN: Subheader -->
<div class="m-subheader">
<div class="d-flex align-items-center">
<div class="mr-auto">
<h3 class="m-subheader__title">
Riders
</h3>
</div>
</div>
</div>
<!-- END: Subheader -->
<div class="m-content">
<!--Begin::Section-->
<div class="row">
<div class="col-xl-12">
<div class="m-portlet m-portlet--mobile">
<div class="m-portlet__body">
<div class="m-form m-form--label-align-right m--margin-top-20 m--margin-bottom-30">
<div class="row align-items-center">
<div class="col-xl-8 order-2 order-xl-1">
<div class="form-group m-form__group row align-items-center">
<div class="col-md-4">
<div class="m-input-icon m-input-icon--left">
<input type="text" class="form-control m-input m-input--solid" placeholder="Search..." id="data-rows-search">
<span class="m-input-icon__icon m-input-icon__icon--left">
<span><i class="la la-search"></i></span>
</span>
</div>
</div>
</div>
</div>
<div class="col-xl-4 order-1 order-xl-2 m--align-right">
<a href="{{ url('rider_create') }}" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
<span>
<i class="la la-user"></i>
<span>New Rider</span>
</span>
</a>
<div class="m-separator m-separator--dashed d-xl-none"></div>
</div>
</div>
</div>
<!--begin: Datatable -->
<div id="data-rows"></div>
<!--end: Datatable -->
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
$(function() {
var options = {
data: {
type: 'remote',
source: {
read: {
url: '{{ url("rider_rows") }}',
method: 'POST',
}
},
saveState: {
cookie: false,
webstorage: false
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
columns: [
{
field: 'id',
title: 'ID',
width: 30
},
{
field: 'first_name',
title: 'First Name'
},
{
field: 'last_name',
title: 'Last Name'
},
{
field: 'contact_num',
title: 'Contact No.'
},
{
field: 'hub',
title: 'Hub'
},
{
field: 'Actions',
width: 110,
title: 'Actions',
sortable: false,
overflow: 'visible',
template: function (row, index, datatable) {
var actions = '';
if (row.meta.update_url != '') {
actions += '<a href="' + row.meta.update_url + '" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill btn-edit" data-id="' + row.first_name + ' ' + row.last_name + '" title="Edit"><i class="la la-edit"></i></a>';
}
if (row.meta.delete_url != '') {
actions += '<a href="' + row.meta.delete_url + '" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill btn-delete" data-id="' + row.first_name + ' ' + row.last_name + '" title="Delete"><i class="la la-trash"></i></a>';
}
return actions;
},
}
],
search: {
onEnter: false,
input: $('#data-rows-search'),
delay: 400
}
};
var table = $("#data-rows").mDatatable(options);
$(document).on('click', '.btn-delete', function(e) {
var url = $(this).prop('href');
var id = $(this).data('id');
var btn = $(this);
e.preventDefault();
swal({
title: 'Confirmation',
html: 'Are you sure you want to delete <strong>' + id + '</strong>?',
type: 'warning',
showCancelButton: true
}).then((result) => {
if (result.value) {
$.ajax({
method: "DELETE",
url: url
}).done(function(response) {
table.row(btn.parents('tr')).remove();
table.reload();
}).fail(function() {
swal({
title: 'Whoops',
text: 'An error occurred while deleting this item. Please contact support.',
type: 'error'
});
});
}
});
});
});
</script>
{% endblock %}