Add CRUD functionalities to Partners. #228

This commit is contained in:
Korina Cordero 2019-07-05 07:26:16 +00:00
parent 56f152fa70
commit d1209d2474
6 changed files with 836 additions and 11 deletions

View file

@ -0,0 +1,33 @@
partner_list:
path: /partners
controller: App\Controller\PartnerController::index
partner_rows:
path: /partners/rows
controller: App\Controller\PartnerController::rows
methods: [POST]
partner_create:
path: /partners/create
controller: App\Controller\PartnerController::addForm
methods: [GET]
partner_create_submit:
path: /partners/create
controller: App\Controller\PartnerController::addSubmit
methods: [POST]
partner_update:
path: /partners/{id}
controller: App\Controller\PartnerController::updateForm
methods: [GET]
partner_update_submit:
path: /partners/{id}
controller: App\Controller\PartnerController::updateSubmit
methods: [POST]
partner_delete:
path: /partners/{id}
controller: App\Controller\PartnerController::destroy
methods: [DELETE]

View file

@ -0,0 +1,314 @@
<?php
namespace App\Controller;
use App\Entity\Partner;
use App\Entity\Service;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use DateTime;
use Catalyst\MenuBundle\Annotation\Menu;
class PartnerController extends Controller
{
/**
* @Menu(selected="partner_list")
*/
public function index()
{
$this->denyAccessUnlessGranted('partner.list', null, 'No access.');
return $this->render('partner/list.html.twig');
}
public function rows(Request $req)
{
$this->denyAccessUnlessGranted('partner.list', null, 'No access.');
// get query builder
$qb = $this->getDoctrine()
->getRepository(Partner::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)');
$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');
$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();
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['name'] = $orow->getName();
$row['branch'] = $orow->getBranch();
$row['address'] = $orow->getAddress();
$row['contact_nums'] = $orow->getContactNumbers();
$row['time_open'] = $orow->getTimeOpen()->format('g:i A');
$row['time_close'] = $orow->getTimeClose()->format('g:i A');
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('partner.update'))
$row['meta']['update_url'] = $this->generateUrl('partner_update', ['id' => $row['id']]);
if ($this->isGranted('hub.delete'))
$row['meta']['delete_url'] = $this->generateUrl('partner_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="partner_list")
*/
public function addForm()
{
$this->denyAccessUnlessGranted('partner.add', null, 'No access.');
$params = [];
$params['obj'] = new Partner();
$params['mode'] = 'create';
$em = $this->getDoctrine()->getManager();
// get services
$params['services'] = $em->getRepository(Service::class)->findAll();
// response
return $this->render('partner/form.html.twig', $params);
}
public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('partner.add', null, 'No access.');
// create new object
$em = $this->getDoctrine()->getManager();
$obj = new Partner();
$this->setObject($obj, $em, $req);
// validate
$errors = $validator->validate($obj);
// 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);
}
// validated! save the entity
$em->persist($obj);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @Menu(selected="partner_list")
*/
public function updateForm($id)
{
$this->denyAccessUnlessGranted('partner.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Partner::class)->find($id);
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$params = [];
$params['obj'] = $obj;
$params['services'] = $em->getRepository(Service::class)->findAll();
$params['mode'] = 'update';
// response
return $this->render('partner/form.html.twig', $params);
}
public function updateSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('partner.update', null, 'No access.');
// get object data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Partner::class)->find($id);
// make sure this object exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$this->setObject($obj, $em, $req);
// validate
$errors = $validator->validate($obj);
// 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);
}
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
public function destroy($id)
{
$this->denyAccessUnlessGranted('partner.delete', null, 'No access.');
// get object data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Partner::class)->find($id);
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
// delete this object
$em->remove($obj);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
protected function setQueryFilters($datatable, QueryBuilder $query)
{
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.name LIKE :filter')
->orWhere('q.address LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
protected function setObject(Partner $obj, EntityManager $em, Request $req)
{
// coordinates
$point = new Point($req->request->get('coord_lng'), $req->request->get('coord_lat'));
// times
$format = 'g:i A';
$time_open = DateTime::createFromFormat($format, $req->request->get('time_open'));
$time_close = DateTime::createFromFormat($format, $req->request->get('time_close'));
// set and save values
$obj->setName($req->request->get('name'))
->setCreatedBy($this->getUser())
->setBranch($req->request->get('branch'))
->setAddress($req->request->get('address'))
->setContactNumbers($req->request->get('contact_nums'))
->setTimeOpen($time_open)
->setTimeClose($time_close)
->setCoordinates($point)
->clearServices();
// set services
$services = $req->request->get('services');
if (!empty($services))
{
foreach($services as $service_id)
{
// check if service exists
$service = $em->getRepository(Service::class)->find($service_id);
if (!empty($service))
$obj->addService($service);
}
}
}
}

View file

@ -47,13 +47,15 @@ class Partner
// services provided // services provided
/** /**
* @ORM\ManyToMany(targetEntity="Service", inversedBy="partners", indexBy="id") * @ORM\ManyToMany(targetEntity="Service", inversedBy="partners")
* @ORM\JoinTable(name="partner_services") * @ORM\JoinTable(name="partner_services")
*/ */
protected $services; protected $services;
public function __construct() public function __construct()
{ {
$this->time_open = new DateTime();
$this->time_close = new DateTime();
$this->services = new ArrayCollection(); $this->services = new ArrayCollection();
$this->date_create = new DateTime(); $this->date_create = new DateTime();
} }
@ -92,15 +94,7 @@ class Partner
public function addService(Service $service) public function addService(Service $service)
{ {
if (!isset($this->services[$service->getID()])) $this->services->add($service);
unset($this->services[$service->getID()]);
return $this;
}
public function removeService(Service $service)
{
if (isset($this->services[$service->getID()]))
unset($this->services[$service->getID()]);
return $this; return $this;
} }
@ -111,6 +105,15 @@ class Partner
} }
public function getServices() public function getServices()
{
$str_services = [];
foreach ($this->services as $service)
$str_services[] = $service->getID();
return $str_services;
}
public function getServicesObjects()
{ {
return $this->services; return $this->services;
} }

View file

@ -30,7 +30,7 @@ class Service
// link to partners with this service // link to partners with this service
/** /**
* @ORM\ManyToMany(targetEntity="Partner", mappedBy="services", indexBy="id", fetch="EXTRA_LAZY") * @ORM\ManyToMany(targetEntity="Partner", mappedBy="services", fetch="EXTRA_LAZY")
*/ */
protected $partners; protected $partners;

View file

@ -0,0 +1,312 @@
{% 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">Partners</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-building"></i>
</span>
<h3 class="m-portlet__head-text">
{% if mode == 'update' %}
Edit Partner
<small>{{ obj.getName() }}</small>
{% else %}
New Partner
{% endif %}
</h3>
</div>
</div>
</div>
<form id="row-form" class="m-form m-form--label-align-right" method="post" action="{{ mode == 'update' ? url('partner_update_submit', {'id': obj.getId()}) : url('partner_create_submit') }}">
<div class="m-portlet__body">
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label for="name" data-field="name">
Name
</label>
<input type="text" name="name" class="form-control m-input" value="{{ obj.getName() }}">
<div class="form-control-feedback hide" data-field="name"></div>
</div>
<div class="col-lg-6">
<label for="branch" data-field="branch">
Branch
</label>
<input type="text" name="branch" class="form-control m-input" value="{{ obj.getBranch() }}">
<div class="form-control-feedback hide" data-field="branch"></div>
</div>
</div>
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label for="address" data-field="address">
Address
</label>
<textarea class="form-control m-input" id="address" rows="4" name="address">{{ obj.getAddress }}</textarea>
<div class="form-control-feedback hide" data-field="address"></div>
</div>
<div class="col-lg-6">
<label for="contact_nums" data-field="contact_nums">
Contact Numbers
</label>
<textarea class="form-control m-input" id="contact_nums" rows="4" name="contact_nums">{{ obj.getContactNumbers }}</textarea>
<div class="form-control-feedback hide" data-field="contact_nums"></div>
</div>
</div>
<div class="form-group m-form__group row no-border">
<div class="col-lg-3">
<label for="time_open">
Time Open
</label>
<div class="input-group timepicker">
<input id="timepicker_open" type="text" name="time_open" class="form-control m-input" readonly placeholder="Select time" type="text" value="{{ obj.getTimeOpen.format('g:i A') }}" />
<span class="input-group-addon">
<i class="la la-clock-o"></i>
</span>
</div>
<div class="form-control-feedback hide" data-field="time_open"></div>
</div>
<div class="col-lg-3">
<label for="time_close">
Time Close
</label>
<div class="input-group timepicker">
<input id="timepicker_close" type="text" name="time_close" class="form-control m-input" readonly placeholder="Select time" type="text" value="{{ obj.getTimeClose.format('g:i A') }}" />
<span class="input-group-addon">
<i class="la la-clock-o"></i>
</span>
</div>
<div class="form-control-feedback hide" data-field="time_close"></div>
</div>
</div>
<div class="form-group m-form__group row">
<div class="col-lg-12">
<label>
Map Coordinates
</label>
<input type="hidden" id="map_lat" name="coord_lat" value="">
<input type="hidden" id="map_lng" name="coord_lng" value="">
<div class="input-group">
<input type="text" class="form-control" id="m_gmap_address" placeholder="Search">
<span class="input-group-btn">
<button class="btn btn-primary" id="m_gmap_btn">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<div id="m_gmap" style="height:600px;"></div>
</div>
</div>
<div class="m-form__seperator m-form__seperator--dashed"></div>
<div class="m-form__section">
<div class="m-form__heading">
<h3 class="m-form__heading-title">
Services
</h3>
</div>
<div class="form-group m-form__group row">
<div class="col-lg-12">
{% if services is empty %}
No services available.
{% else %}
<div class="m-checkbox-list">
{% for service in services %}
<label class="m-checkbox">
<input type="checkbox" name="services[]" value="{{ service.getID() }}"{{ service.getID() in obj.getServices() ? ' checked' : '' }}>
{{ service.getName() }}
<span></span>
</label>
{% endfor %}
</div>
<div class="form-control-feedback hide" data-field="services"></div>
<span class="m-form__help">Check all services that apply</span>
{% endif %}
</div>
</div>
</div>
</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('partner_list') }}" class="btn btn-secondary">Back</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
{% endblock %}
{% block scripts %}
<script src="//maps.google.com/maps/api/js?key={{ gmaps_api_key }}" type="text/javascript"></script>
<script src="/assets/vendors/custom/gmaps/gmaps.js" type="text/javascript"></script>
<script>
// BEGIN google maps stuff
function selectPoint(map, latlng) {
var lat = latlng.lat();
var lng = latlng.lng();
// show it in map
map.removeMarkers();
map.setCenter(lat, lng);
map.addMarker({
lat: lat,
lng: lng
});
// set value in hidden input
$('#map_lat').val(lat);
$('#map_lng').val(lng);
}
var map = new GMaps({
div: '#m_gmap',
lat: 14.6091,
lng: 121.0223,
click: function(e) {
// handle click in map
selectPoint(map, e.latLng);
e.stop();
}
});
var handleAction = function() {
var text = $.trim($('#m_gmap_address').val());
GMaps.geocode({
address: text,
callback: function(results, status) {
map.removeMarkers();
if (status == 'OK') {
selectPoint(map, results[0].geometry.location);
}
},
region: 'ph'
});
}
$('#m_gmap_btn').click(function(e) {
e.preventDefault();
handleAction();
});
$("#m_gmap_address").keypress(function(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == '13') {
e.preventDefault();
handleAction();
}
});
// END google maps stuff
$(document).ready(function() {
// timepickers
$('#timepicker_open, #timepicker_close').timepicker({
format: "HH:ii P",
minuteStep: 1,
showMeridian: true,
snapToStep: true,
bootcssVer: 3,
todayHighlight: true,
autoclose: true
});
// check if we need to set map
{% if mode == 'update' %}
var latlng = new google.maps.LatLng({{ obj.getCoordinates.getLatitude }}, {{ obj.getCoordinates.getLongitude }});
selectPoint(map, latlng);
{% endif %}
});
$(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('partner_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">
Partners
</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('partner_create') }}" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
<span>
<i class="fa fa-building"></i>
<span>New Partner</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("partner_rows") }}',
method: 'POST',
}
},
saveState: {
cookie: false,
webstorage: false
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
columns: [
{
field: 'id',
title: 'ID',
width: 30
},
{
field: 'name',
title: 'Hub'
},
{
field: 'branch',
title: 'Branch'
},
{
field: 'address',
title: 'Address'
},
{
field: 'contact_nums',
title: 'Contact Numbers'
},
{
field: 'time_open',
title: 'Time Open'
},
{
field: 'time_close',
title: 'Time Close'
},
{
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.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.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();
});
}
});
});
});
</script>
{% endblock %}