Use server side form submission and validation for user crud

This commit is contained in:
Ramon Gutierrez 2018-01-10 04:29:51 +08:00
parent 7926bf8a75
commit 027f017d6f
3 changed files with 223 additions and 109 deletions

View file

@ -10,6 +10,7 @@ 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 UserController extends BaseController
{
@ -112,47 +113,80 @@ class UserController extends BaseController
return $this->render('user/form.html.twig', $params);
}
public function createSubmit(Request $req, EncoderFactoryInterface $ef)
public function createSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator)
{
// TODO: validation, compare password fields
// create new row
$em = $this->getDoctrine()->getManager();
$row = new User();
// encode password
$enc = $ef->getEncoder($row);
$password = $enc->encodePassword($req->request->get('password'), $row->getSalt());
// set and save values
$row->setUsername($req->request->get('username'))
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setPassword($password)
->setEmail($req->request->get('email'))
->setContactNumber($req->request->get('contact_no'))
->setEnabled($req->request->get('enabled') ? true : false);
->setEnabled($req->request->get('enabled') ? true : false)
->clearRoles();
// set roles
foreach ($req->request->get('roles') as $role_id) {
// check if role exists
$role = $em->getRepository(Role::class)->find($role_id);
$roles = $req->request->get('roles');
if (!empty($role))
$row->addRole($role);
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);
}
}
$em->persist($row);
$em->flush();
// validate
$errors = $validator->validate($row);
// set success
$this->addFlash(
'success',
'Changes have been saved!'
);
// initialize error list
$error_array = [];
// response
return $this->redirectToRoute('user_list');
// 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 update($id)
@ -163,6 +197,7 @@ class UserController extends BaseController
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(User::class)->find($id);
// make sure this row exists
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
@ -177,12 +212,13 @@ class UserController extends BaseController
return $this->render('user/form.html.twig', $params);
}
public function updateSubmit(Request $req, EncoderFactoryInterface $ef, $id)
public function updateSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, $id)
{
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(User::class)->find($id);
// make sure this row exists
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
@ -195,37 +231,64 @@ class UserController extends BaseController
->setEnabled($req->request->get('enabled') ? true : false)
->clearRoles();
// update password if provided
$password_input = $req->request->get('password');
$confirm_password_input = $req->request->get('confirm_password');
if ($password_input || $confirm_password_input) {
// encode password
$enc = $ef->getEncoder($row);
$password = $enc->encodePassword($req->request->get('password'), $row->getSalt());
$row->setPassword($password);
}
// set roles
foreach ($req->request->get('roles') as $role_id) {
// check if role exists
$role = $em->getRepository(Role::class)->find($role_id);
$roles = $req->request->get('roles');
if (!empty($role))
$row->addRole($role);
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);
}
}
$em->flush();
// validate
$errors = $validator->validate($row);
// set success
$this->addFlash(
'success',
'Changes have been saved!'
);
// initialize error list
$error_array = [];
// response
return $this->redirectToRoute('user_list');
// 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)

View file

@ -32,86 +32,72 @@
</div>
</div>
</div>
<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" method="post" action="{{ row is defined ? url('user_update_submit', {'id': row.getId()}) : url('user_create_submit') }}">
<form id="row-form" class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" method="post" action="{{ row is defined ? url('user_update_submit', {'id': row.getId()}) : url('user_create_submit') }}">
<div class="m-portlet__body">
<div class="form-group m-form__group row">
<label class="col-lg-2 col-form-label">
<div class="form-group m-form__group row no-border">
<label class="col-lg-2 col-form-label" data-field="username">
Username:
</label>
<div class="col-lg-4{{ error.username is defined ? ' has-danger' }}">
<input type="text" name="username" class="form-control m-input{{ error.username is defined ? ' form-control-danger' }}" value="{{ values.username is defined ? values.username : (row is defined ? row.getUsername()) }}">
{% if error.username is defined %}
<div class="form-control-feedback">{{ error.username }}</div>
{% endif %}
<div class="col-lg-4">
<input type="text" name="username" class="form-control m-input" value="{{ values.username is defined ? values.username : (row is defined ? row.getUsername()) }}">
<div class="form-control-feedback hide" data-field="username"></div>
<span class="m-form__help">Unique alias for this user</span>
</div>
</div>
<div class="form-group m-form__group row">
<label class="col-lg-2 col-form-label">
First Name:
</label>
<div class="col-lg-4{{ error.first_name is defined ? ' has-danger' }}">
<input type="text" name="first_name" class="form-control m-input{{ error.first_name is defined ? ' form-control-danger' }}" value="{{ values.first_name is defined ? values.first_name : (row is defined ? row.getFirstName()) }}">
{% if error.first_name is defined %}
<div class="form-control-feedback">{{ error.first_name }}</div>
{% endif %}
</div>
<label class="col-lg-2 col-form-label">
Last Name:
</label>
<div class="col-lg-4{{ error.last_name is defined ? ' has-danger' }}">
<input type="text" name="last_name" class="form-control m-input{{ error.last_name is defined ? ' form-control-danger' }}" value="{{ values.last_name is defined ? values.last_name : (row is defined ? row.getLastName()) }}">
{% if error.last_name is defined %}
<div class="form-control-feedback">{{ error.last_name }}</div>
{% endif %}
</div>
</div>
<div class="form-group m-form__group row">
<label class="col-lg-2 col-form-label">
<label class="col-lg-2 col-form-label" data-field="password">
Password:
</label>
<div class="col-lg-4{{ error.password is defined ? ' has-danger' }}">
<input type="password" name="password" class="form-control m-input{{ error.password is defined ? ' form-control-danger' }}">
{% if error.password is defined %}
<div class="form-control-feedback">{{ error.password }}</div>
{% endif %}
<div class="col-lg-4">
<input type="password" name="password" class="form-control m-input">
<div class="form-control-feedback hide" data-field="password"></div>
{% if row is defined %}
<span class="m-form__help">Leave both fields blank for unchanged</span>
{% endif %}
</div>
<label class="col-lg-2 col-form-label">
<label class="col-lg-2 col-form-label" data-field="confirm_password">
Confirm Password:
</label>
<div class="col-lg-4{{ error.confirm_password is defined ? ' has-danger' }}">
<input type="password" name="confirm_password" class="form-control m-input{{ error.confirm_password is defined ? ' form-control-danger' }}">
{% if error.confirm_password is defined %}
<div class="form-control-feedback">{{ error.confirm_password }}</div>
{% endif %}
<div class="col-lg-4">
<input type="password" name="confirm_password" class="form-control m-input">
<div class="form-control-feedback hide" data-field="confirm_password"></div>
</div>
</div>
<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="{{ values.first_name is defined ? values.first_name : (row is defined ? row.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="{{ values.last_name is defined ? values.last_name : (row is defined ? row.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">
<label class="col-lg-2 col-form-label" data-field="email">
E-mail Address:
</label>
<div class="col-lg-4{{ error.email is defined ? ' has-danger' }}">
<input type="email" name="email" class="form-control m-input{{ error.email is defined ? ' form-control-danger' }}" value="{{ values.email is defined ? values.email : (row is defined ? row.getEmail()) }}">
{% if error.email is defined %}
<div class="form-control-feedback">{{ error.email }}</div>
{% endif %}
<div class="col-lg-4">
<input type="email" name="email" class="form-control m-input" value="{{ values.email is defined ? values.email : (row is defined ? row.getEmail()) }}">
<div class="form-control-feedback hide" data-field="email"></div>
</div>
<label class="col-lg-2 col-form-label">
<label class="col-lg-2 col-form-label" data-field="contact_no">
Contact Number:
</label>
<div class="col-lg-4{{ error.contact_no is defined ? ' has-danger' }}">
<input type="text" name="contact_no" class="form-control m-input{{ error.contact_no is defined ? ' form-control-danger' }}" value="{{ values.contact_no is defined ? values.contact_no : (row is defined ? row.getContactNumber()) }}">
{% if error.contact_no is defined %}
<div class="form-control-feedback">{{ error.contact_no }}</div>
{% endif %}
<div class="col-lg-4">
<input type="text" name="contact_no" class="form-control m-input" value="{{ values.contact_no is defined ? values.contact_no : (row is defined ? row.getContactNumber()) }}">
<div class="form-control-feedback hide" data-field="contact_no"></div>
</div>
</div>
<div class="form-group m-form__group row">
<label class="col-lg-2 col-form-label">
<label class="col-lg-2 col-form-label" data-field="roles">
Roles:
</label>
<div class="col-lg-10">
@ -124,11 +110,12 @@
</label>
{% endfor %}
</div>
<div class="form-control-feedback hide" data-field="roles"></div>
<span class="m-form__help">Check all roles that apply</span>
</div>
</div>
<div class="form-group m-form__group row">
<label class="col-lg-2 col-form-label">
<label class="col-lg-2 col-form-label" data-field="enabled">
Enabled:
</label>
<div class="col-lg-10">
@ -138,6 +125,7 @@
<span></span>
</label>
</span>
<div class="form-control-feedback hide" data-field="enabled"></div>
</div>
</div>
</div>
@ -156,4 +144,73 @@
</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('user_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

@ -18,12 +18,6 @@
<div class="col-xl-12">
<div class="m-portlet m-portlet--mobile">
<div class="m-portlet__body">
{% for message in app.flashes('success') %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>
<strong>Success!</strong> {{ message }}
</div>
{% endfor %}
<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">