Skip to content

Commit

Permalink
feature #155 Added click-to-toggle for boolean columns (javiereguiluz)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the master branch (closes #155).

Discussion
----------

Added click-to-toggle for boolean columns

This PR allows to click on any boolean value displayed in a listing to toggle its value: if you click on a `YES` value, you change it to `NO` and *vice versa*.

This is a WIP pull request to hear your opinions: I need to clean JavaScript code a bit, add PHPdoc, document the feature, etc.

I first saw this cool feature in SonataAdmin. I don't know if this feature is an original idea of Sonata project or if they copied it from someone else. In any case, thanks to whoever invented this feature and all the credits for the idea goes to him/her.

-----

**This is how it works**

1) If the boolean column corresponds to an entity property, you now can click on it to toggle its value:

![toggle_1](https://cloud.githubusercontent.com/assets/73419/6515398/bd82628e-c389-11e4-8106-60b19299f845.gif)

2) If the boolean column is a virtual field, you cannot click on it to toggle its value:

![toggle_2](https://cloud.githubusercontent.com/assets/73419/6515406/d241e97e-c389-11e4-859b-0affe892c958.gif)

3) When things go right, clicking on a boolean column toggles its value without having to edit the entity:

![toggle_3](https://cloud.githubusercontent.com/assets/73419/6515413/ee384d1c-c389-11e4-926a-5b913d9af8c7.gif)

4) If some error happens, the label shows a warning `ERROR` message until the page is reloaded:

![toggle_4](https://cloud.githubusercontent.com/assets/73419/6515418/fc183230-c389-11e4-9064-b3265db1abe9.gif)

Commits
-------

d08dcd8 Added click-to-toggle for boolean columns
  • Loading branch information
javiereguiluz committed Mar 7, 2015
2 parents fd8c37d + d08dcd8 commit e2c10a1
Show file tree
Hide file tree
Showing 6 changed files with 179 additions and 9 deletions.
49 changes: 48 additions & 1 deletion Controller/AdminController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
Expand All @@ -33,7 +34,7 @@
*/
class AdminController extends Controller
{
protected $allowedActions = array('list', 'edit', 'new', 'show', 'search', 'delete');
protected $allowedActions = array('list', 'edit', 'new', 'show', 'search', 'delete', 'toggle');
protected $config;
protected $entity = array();

Expand Down Expand Up @@ -267,6 +268,52 @@ protected function searchAction()
));
}

protected function toggleAction()
{
if (!$entity = $this->em->getRepository($this->entity['class'])->find($this->request->query->get('id'))) {
throw new \Exception('The entity does not exist.');
}

$propertyName = $this->request->query->get('property');
if (!isset($this->entity['properties'][$propertyName])
|| 'boolean' != $this->entity['properties'][$propertyName]['type']) {
throw new \Exception(sprintf('The "%s" property is not boolean.', $propertyName));
}

// get the current property value
$getter = 'get'.ucfirst($propertyName);
$isser = 'is'.ucfirst($propertyName);

if (method_exists($entity, $getter)) {
$value = $entity->{$getter}();
} elseif (method_exists($entity, $isser)) {
$value = $entity->{$isser}();
} elseif (property_exists($entity, $propertyName)) {
$value = $entity->{$propertyName};
} else {
throw new \Exception(sprintf('It\'s not possible to get the current value of the "%s" boolean property of the "%s" entity.', $propertyName, $this->entity['name']));
}

// toggle the property value
$newValue = !$value;
$setter = 'set'.ucfirst($propertyName);
$isser = 'setIs'.ucfirst($propertyName);

if (method_exists($entity, $setter)) {
$entity->{$setter}($newValue);
} elseif (method_exists($entity, $isser)) {
$entity->{$isser}($newValue);
} elseif (property_exists($entity, $propertyName)) {
$entity->{$propertyName} = $newValue;
} else {
throw new \Exception(sprintf('It\'s not possible to toggle the value of the "%s" boolean property of the "%s" entity.', $propertyName, $this->entity['name']));
}

$this->em->flush();

return new Response(true === $newValue ? 'on' : 'off');
}

/**
* Allows applications to modify the entity associated with the item being
* edited before persisting it.
Expand Down
8 changes: 8 additions & 0 deletions Resources/public/javascript/bootstrap-toggle.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 46 additions & 3 deletions Resources/public/stylesheet/admin.css
Original file line number Diff line number Diff line change
Expand Up @@ -202,20 +202,63 @@ ul.pager .next {

/* Labels
------------------------------------------------------------------------- */
span.label {
.label {
background: #222;
color: #FFF;
font-size: 11px;
padding: 2px 4px;
text-transform: uppercase;
}
span.label-success {
.label-success {
background: #00994D;
}
span.label-danger {
.label-warning {
background: #FFFF61;
color: #222;
}
.label-danger {
background: #D44542;
}

/* Switches / toggles
------------------------------------------------------------------------- */
.boolean .btn {
border-radius: 3px;
font-size: 11px;
font-weight: bold;
}
.boolean .toggle.btn-success {
border-color: #398439;
background: #00994D;
}
.boolean .toggle.btn-danger {
border-color: #AC2925;
background: #D0322F;
}
.boolean .btn-success .toggle-handle {
box-shadow: -2px 0 1px #008040;
}
.boolean .btn-danger .toggle-handle {
box-shadow: 2px 0 1px #BB2D2A;
}
.boolean .toggle .toggle-on {
background: #00994D;
}
.boolean .toggle .toggle-off {
background: #D0322F;
}
.boolean .toggle-group label {
padding-top: 2px;
}
.boolean .toggle.btn-xs {
width: 44px;
}
.boolean .toggle.btn-xs .toggle-handle {
height: 18px;
margin-top: 1px;
margin-right: 5px;
}

/* Badges
------------------------------------------------------------------------- */
span.badge {
Expand Down
28 changes: 28 additions & 0 deletions Resources/public/stylesheet/bootstrap-toggle.min.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*! ========================================================================
* Bootstrap Toggle: bootstrap-toggle.css v2.2.0
* http://www.bootstraptoggle.com
* ========================================================================
* Copyright 2014 Min Hur, The New York Times Company
* Licensed under MIT
* ======================================================================== */
.checkbox label .toggle,.checkbox-inline .toggle{margin-left:-20px;margin-right:5px}
.toggle{position:relative;overflow:hidden}
.toggle input[type=checkbox]{display:none}
.toggle-group{position:absolute;width:200%;top:0;bottom:0;left:0;transition:left .35s;-webkit-transition:left .35s;-moz-user-select:none;-webkit-user-select:none}
.toggle.off .toggle-group{left:-100%}
.toggle-on{position:absolute;top:0;bottom:0;left:0;right:50%;margin:0;border:0;border-radius:0}
.toggle-off{position:absolute;top:0;bottom:0;left:50%;right:0;margin:0;border:0;border-radius:0}
.toggle-handle{position:relative;margin:0 auto;padding-top:0;padding-bottom:0;height:100%;width:0;border-width:0 1px}
.toggle.btn{min-width:59px;min-height:34px}
.toggle-on.btn{padding-right:24px}
.toggle-off.btn{padding-left:24px}
.toggle.btn-lg{min-width:79px;min-height:45px}
.toggle-on.btn-lg{padding-right:31px}
.toggle-off.btn-lg{padding-left:31px}
.toggle-handle.btn-lg{width:40px}
.toggle.btn-sm{min-width:50px;min-height:30px}
.toggle-on.btn-sm{padding-right:20px}
.toggle-off.btn-sm{padding-left:20px}
.toggle.btn-xs{min-width:35px;min-height:22px}
.toggle-on.btn-xs{padding-right:12px}
.toggle-off.btn-xs{padding-left:12px}
49 changes: 47 additions & 2 deletions Resources/views/list.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
{% trans_default_domain "EasyAdminBundle" %}
{% block body_class 'admin list ' ~ entity.name|lower %}

{% block head_stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('bundles/easyadmin/stylesheet/bootstrap-toggle.min.css') }}">
{% endblock %}

{% block content_title %}
{% if 'search' == app.request.get('action') %}
{{ 'search.page_title'|transchoice(paginator.nbResults)|raw }}
Expand Down Expand Up @@ -49,7 +54,7 @@
{% for field, metadata in fields %}
{% set isSortingField = metadata.property == app.request.get('sortField') %}

<th class="{{ isSortingField ? 'sorted' : '' }} {{ metadata.type|lower }}">
<th data-property-name="{{ metadata.property }}" class="{{ isSortingField ? 'sorted' : '' }} {{ metadata.virtual|default(false) ? 'virtual' : '' }} {{ metadata.type|lower }}">
{% if isSortingField %}
{% set sortDirection = ('DESC' == app.request.get('sortDirection')) ? 'ASC' : 'DESC' %}
{% set request_attributes = request_attributes|merge({ sortField: metadata.property }) %}
Expand Down Expand Up @@ -91,7 +96,7 @@

<tbody>
{% for item in paginator.currentPageResults %}
<tr>
<tr data-id="{{ attribute(item, entity.primary_key_field_name) }}">
{% for field, metadata in fields %}
{% set isSortingField = metadata.property == app.request.get('sortField') %}

Expand Down Expand Up @@ -124,3 +129,43 @@
</div>
</div>
{% endblock %}

{% block body_javascript %}
{{ parent() }}

<script src="{{ asset('bundles/easyadmin/javascript/bootstrap-toggle.min.js') }}"></script>

<script type="text/javascript">
$(function() {
$('#main table .boolean .toggle input[type="checkbox"]').change(function() {
var toggle = $(this);
var newValue = toggle.prop('checked');
var oldValue = !newValue;
var columnIndex = $(this).closest('td').index() + 1;
var propertyName = $('table th.boolean:nth-child(' + columnIndex + ')').data('property-name');
var toggleUrl = "{{ path('admin', { action: 'toggle', entity: entity.name })|raw }}"
+ "&property=" + propertyName
+ "&id=" + $(this).closest('tr').data('id');
var toggleRequest = $.ajax({ type: "GET", url: toggleUrl, data: {} });
toggleRequest.done(function(result) {
// protection against race conditions: if the persisted value
// doesn't match the new value, change it to avoid confusions
var persistedValue = ('on' == result) ? true : false;
if (persistedValue != newValue) {
toggle.bootstrapToggle(persistedValue == true ? 'on' : 'off');
}
});
toggleRequest.fail(function(result) {
// in case of error, restore the original value and disable the toggle
toggle.bootstrapToggle(oldValue == true ? 'on' : 'off');
toggle.bootstrapToggle('disable');
});
});
});
</script>
{% endblock %}
5 changes: 2 additions & 3 deletions Twig/EasyAdminTwigExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,8 @@ public function displayEntityField($entity, $fieldName, array $fieldMetadata)
}

if (in_array($fieldType, array('boolean'))) {
return new \Twig_Markup(sprintf('<span class="label label-%s">%s</span>',
true === $value ? 'success' : 'danger',
true === $value ? 'YES' : 'NO'
return new \Twig_Markup(sprintf('<input type="checkbox" %s data-toggle="toggle" data-size="mini" data-onstyle="success" data-offstyle="danger" data-on="YES" data-off="NO">',
true === $value ? 'checked' : ''
), 'UTF-8');
}

Expand Down

0 comments on commit e2c10a1

Please sign in to comment.