Add create, list, update, and delete for SAP Battery. #524

This commit is contained in:
Korina Cordero 2020-11-27 09:52:24 +00:00
parent bd80c6295a
commit 0752fe3726
7 changed files with 669 additions and 8 deletions

View file

@ -67,7 +67,7 @@ main_menu:
acl: sap_battery.menu
label: SAP Battery
icon: fa fa-battery
- id: sapbattery.list
- id: sapbattery_list
acl: sap_battery.list
label: SAP Batteries
parent: sapbattery

View file

@ -15,7 +15,7 @@ use Catalyst\MenuBundle\Annotation\Menu;
class SAPBatteryBrandController extends Controller
{
/**
* @Menu(selected="sap_brand_list")
* @Menu(selected="sapbrand_list")
*/
public function index()
{
@ -117,7 +117,7 @@ class SAPBatteryBrandController extends Controller
}
/**
* @Menu(selected="sap_brand_list")
* @Menu(selected="sapbrand_list")
*/
public function addForm()
{
@ -172,7 +172,7 @@ class SAPBatteryBrandController extends Controller
}
/**
* @Menu(selected="sap_brand_list")
* @Menu(selected="sapbrand_list")
*/
public function updateForm($id)
{

View file

@ -0,0 +1,332 @@
<?php
namespace App\Controller;
use App\Entity\SAPBattery;
use App\Entity\SAPBatteryBrand;
use App\Entity\SAPBatterySize;
use Doctrine\ORM\Query;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Catalyst\MenuBundle\Annotation\Menu;
class SAPBatteryController extends Controller
{
/**
* @Menu(selected="sapbattery_list")
*/
public function index()
{
$this->denyAccessUnlessGranted('sap_battery.list', null, 'No access.');
return $this->render('sap-battery/list.html.twig');
}
public function rows(Request $req)
{
$this->denyAccessUnlessGranted('sap_battery.list', null, 'No access.');
// build query
$qb = $this->getDoctrine()
->getRepository(SAPBattery::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)')
->join('q.brand', 'brand')
->join('q.size', 'size');
// 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('brand.name as brand_name')
->addSelect('size.name as size_name');;
// add filters to query
$this->setQueryFilters($datatable, $query);
// check if filter is present
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.id LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$prefix = '';
if (!in_array($datatable['sort']['field'], ['brand_name', 'size_name']))
$prefix = 'q.';
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy($prefix . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow[0]->getID();
$row['brand_name'] = $orow['brand_name'];
$row['size_name'] = $orow['size_name'];
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('sap_battery.update'))
$row['meta']['update_url'] = $this->generateUrl('sapbattery_update', ['id' => $row['id']]);
if ($this->isGranted('sap_bsize.delete'))
$row['meta']['delete_url'] = $this->generateUrl('sapbattery_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="sapbattery_list")
*/
public function addForm()
{
$this->denyAccessUnlessGranted('sap_battery.add', null, 'No access.');
$params['obj'] = new SAPBattery();
$params['mode'] = 'create';
$em = $this->getDoctrine()->getManager();
// get parent associations
$params['brands'] = $em->getRepository(SAPBatteryBrand::class)->findAll();
$params['sizes'] = $em->getRepository(SAPBatterySize::class)->findAll();
// response
return $this->render('sap-battery/form.html.twig', $params);
}
public function addSubmit(Request $req, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('sap_battery.add', null, 'No access.');
// create new row
$em = $this->getDoctrine()->getManager();
$row = new SAPBattery();
// set and save values
$row->setID($req->request->get('id'));
// custom validation for battery brand
$brand = $em->getRepository(SAPBatteryBrand::class)
->find($req->request->get('brand'));
if (empty($brand))
$error_array['brannd'] = 'Invalid brand selected.';
else
$row->setBrand($brand);
// custom validation for battery size
$size = $em->getRepository(SAPBatterySize::class)
->find($req->request->get('size'));
if (empty($size))
$error_array['size'] = 'Invalid size selected.';
else
$row->setSize($size);
// validate
$errors = $validator->validate($row);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// 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!'
]);
}
}
/**
* @Menu(selected="sapbattery_list")
*/
public function updateForm($id)
{
$this->denyAccessUnlessGranted('sap_battery.update', null, 'No access.');
$params['mode'] = 'update';
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(SAPBattery::class)->find($id);
// make sure this row exists
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
// get parent associations
$params['brands'] = $em->getRepository(SAPBatteryBrand::class)->findAll();
$params['sizes'] = $em->getRepository(SAPBatterySize::class)->findAll();
$params['obj'] = $row;
// response
return $this->render('sap-battery/form.html.twig', $params);
}
public function updateSubmit(Request $req, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('sap_battery.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(SAPBattery::class)->find($id);
// make sure this row exists
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
// set and save values
$row->setID($req->request->get('id'));
// custom validation for battery brand
$brand = $em->getRepository(SAPBatteryBrand::class)
->find($req->request->get('brand'));
if (empty($brand))
$error_array['brand'] = 'Invalid brand selected.';
else
$row->setBrand($brand);
// custom validation for battery size
$size = $em->getRepository(SAPBatterySize::class)
->find($req->request->get('size'));
if (empty($size))
$error_array['size'] = 'Invalid size selected.';
else
$row->setSize($size);
// validate
$errors = $validator->validate($row);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// 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('sap_battery.delete', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(SAPBattery::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('q.id LIKE :filter')
->orWhere('brand.name LIKE :filter')
->orWhere('size.name LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -15,7 +15,7 @@ use Catalyst\MenuBundle\Annotation\Menu;
class SAPBatterySizeController extends Controller
{
/**
* @Menu(selected="sap_bsize_list")
* @Menu(selected="sapbsize_list")
*/
public function index()
{
@ -117,7 +117,7 @@ class SAPBatterySizeController extends Controller
}
/**
* @Menu(selected="sap_bsize_list")
* @Menu(selected="sapbsize_list")
*/
public function addForm()
{
@ -172,7 +172,7 @@ class SAPBatterySizeController extends Controller
}
/**
* @Menu(selected="sap_bsize_list")
* @Menu(selected="sapbsize_list")
*/
public function updateForm($id)
{

View file

@ -41,7 +41,7 @@
<div class="col-lg-9">
<input type="text" name="name" class="form-control m-input" value="{{ obj.getName() }}">
<div class="form-control-feedback hide" data-field="name"></div>
<span class="m-form__help">Display name for this brand</span>
<span class="m-form__help">Display name for this size</span>
</div>
</div>
</div>

View file

@ -0,0 +1,166 @@
{% 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">SAP Batteries</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__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon">
<i class="fa fa-battery-3"></i>
</span>
<h3 class="m-portlet__head-text">
{% if mode == 'update' %}
Edit SAP Battery
<small>{{ obj.getID }}</small>
{% else %}
New SAP Battery
{% endif %}
</h3>
</div>
</div>
</div>
<form id="row-form" class="m-form m-form--fit m-form--label-align-right" method="post" action="{{ mode == 'update' ? url('sapbattery_update_submit', {'id': obj.getID }) : url('sapbattery_create_submit') }}">
<div class="m-portlet__body">
<div class="m-form__section m-form__section--first">
<div class="m-form__heading">
<h3 class="m-form__heading-title">
Product Details
</h3>
</div>
<div class="form-group m-form__group row">
<div class="col-lg-4">
<label data-field="id">
SAP Code
</label>
<input type="text" name="id" class="form-control m-input" value="{{ obj.getID }}">
<div class="form-control-feedback hide" data-field="id"></div>
</div>
<div class="col-lg-4">
<label data-field="brand">
Brand
</label>
<select class="form-control m-input" id="brand" name="brand">
<option value=""></option>
{% for brand in brands %}
<option value="{{ brand.getID }}"{{ brand.getID == obj.getBrand.getID|default(0) ? ' selected' }}>{{ brand.getName }}</option>
{% endfor %}
</select>
<div class="form-control-feedback hide" data-field="brand"></div>
</div>
<div class="col-lg-4">
<label data-field="size">
Size
</label>
<select class="form-control m-input" id="size" name="size">
<option value=""></option>
{% for size in sizes %}
<option value="{{ size.getID }}"{{ obj.getSize.getID|default(0) == size.getID ? ' selected' }}>{{ size.getName }}</option>
{% endfor %}
</select>
<div class="form-control-feedback hide" data-field="size"></div>
</div>
</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('sapbattery_list') }}" class="btn btn-secondary">Back</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
$(function() {
$("#row-form").submit(function(e) {
var form = $(this);
var formdata = form.serialize();
e.preventDefault();
$.ajax({
method: "POST",
url: form.prop('action'),
data: formdata
}).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('sapbattery_list') }}";
}
});
}).fail(function(response) {
if (response.status == 422) {
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,163 @@
{% 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">
SAP Batteries
</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('sapbattery_create') }}" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
<span>
<i class="fa fa-battery-3"></i>
<span>New SAP Battery</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("sapbattery_rows") }}',
method: 'POST'
}
},
saveState: {
cookie: false,
webstorage: false
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
layout: {
scroll: true
},
columns: [
{
field: 'id',
title: 'ID',
width: 150
},
{
field: 'image_file',
title: '',
sortable: false,
width: 40,
template: function (row, index, datatable) {
var html = '<div class="user-portrait-sm" style="background-image: url(\'' + (row.image_file ? "/uploads/" + row.image_file : "/assets/images/battery.gif") + '\');"></div>';
return html;
}
},
{
field: 'brand_name',
title: 'Brand',
width: 150
},
{
field: 'size_name',
title: 'Size',
width: 180
},
{
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.id + '" 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.id + '" 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();
});
}
});
});
});
</script>
{% endblock %}