-
Notifications
You must be signed in to change notification settings - Fork 119
Fix checkbox array binding #78
Fix checkbox array binding #78
Conversation
…logic to checkBinding().
Ready for review 🎱 |
@@ -76,11 +76,14 @@ protected function setChecked($checked = true) | |||
|
|||
protected function checkBinding() | |||
{ | |||
$currentValue = $this->getAttribute('value'); | |||
$currentValue = (string) $this->getAttribute('value'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you explain all the string casting stuff in more detail and what the issue was that made you need to do it? It would be nice if it's avoidable.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure man. So at first ===
made sense to me, but then this happened. I was minding my own business trying to implement simple radios with binary values...
$form->radio('published', 1)->render();
$form->radio('published', 0)->render();
In context of Laravel/Eloquent, these values are not cast to integers unless I setup an accessor on my model and intval() the thing. However, the value stored on the field object is stored as integer. So by default the old input provider shows the user's selected value as string, but the value on the element object is integer, causing this 1 === "1"
to not bind the old input.
The problem is, we can't simply 1 == "1"
. Imagine this scenario...
<input type="radio" name="published" value="0">
If there is no old value ($oldValue on the field object is then null
), then doing a 0 == null
equates to true, and the radio is checked, as if it were old input! So in this case we DO WANT ===
, but in the first case we don't want ===
.
Casting everything to string before comparing values solves both problems. TL;DR... The HTML value attribute on checkboxes/radios knows nothing about an integer, or anything about data types or null
values for that matter. All it knows is string value. If we cast everything to string first, we get a more accurate comparison of old input in all cases.
Old input and model binding worked fine multiple selects (this PR adds test coverage to prove this):
But doesn't work on checkbox arrays:
This PR adds test coverage and a proposed fix for checkbox array old input and model binding.