Skip to content

Instantly share code, notes, and snippets.

@amberlex78
Last active December 15, 2021 08:02
Show Gist options
  • Save amberlex78/d6983ade1a0f56314c5d56bf5d8a3432 to your computer and use it in GitHub Desktop.
Save amberlex78/d6983ade1a0f56314c5d56bf5d8a3432 to your computer and use it in GitHub Desktop.
Symfony 5.4, PHP 8: Change bool status with error handling
<div class="form-check form-switch">
<label>
<input {{ value ? 'checked' : '' }}
{% if field is defined %}data-field="{{ field }}"{% endif %}
data-entity="{{ get_class(entity) }}"
data-path="{{ path('admin_ajax_change_boolean', {'id': entity.id}) }}"
data-_token="{{ csrf_token('check' ~ entity.id ) }}"
class="form-check-input js-checkbox-status"
type="checkbox" style="cursor: pointer">
</label>
</div>
<?php
namespace App\Controller\Admin;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/admin/ajax', name: 'admin_ajax_')]
class AjaxController extends AbstractController
{
public const FIELD_IS_ACTIVE = 'isActive';
public const ALLOWED_FIELDS = [
self::FIELD_IS_ACTIVE,
];
private array $response = [
'success' => false,
'message' => 'Bad Request!',
];
public function __construct(
private EntityManagerInterface $em
) {
}
#[Route('/change/{id<\d+>}/boolean', name: 'change_boolean', methods: ['PATCH'])]
public function changeBoolean(int $id, Request $request): JsonResponse
{
$entity = $request->request->get('entity');
$field = $request->request->get('field') ?? self::FIELD_IS_ACTIVE;
$token = $request->request->get('_token');
if (in_array($field, self::ALLOWED_FIELDS)) {
$fieldSet = 'set' . $field;
$fieldGet = 'get' . $field;
} else {
$this->response['message'] = 'Invalid field to change!';
return $this->json($this->response, 500);
}
if (!$entity = $this->em->getRepository($entity)->findOneBy(['id' => $id])) {
$this->response['message'] = 'Not Found!';
return $this->json($this->response, 404);
}
if ($request->isXmlHttpRequest() && $this->isCsrfTokenValid('check' . $id, $token)) {
$entity->$fieldSet(!$entity->$fieldGet());
$this->em->flush();
return $this->json(
$this->response = [
'success' => true,
'message' => $entity->getIsActive(),
]
);
}
return $this->json($this->response, 400);
}
}
$(function () {
// Change status entity in the list
$('.js-checkbox-status').on('click', function (e) {
$.ajax({
method: 'PATCH',
url: this.dataset.path,
data: this.dataset
})
})
})
<td>
{% include 'admin/_embed/_form/_field_checkbox.html.twig' with {'entity': category, 'value': category.isActive } %}
</td>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment