简体   繁体   中英

Checkbox old value in Laravel form model binding

I have a form I'm trying to build using Form Model Binding (which is something new to me) and I have come across checkboxes that don't want to work with me for some reason.

I have two checkboxes that go to the same field in my database. At the moment I have them formatted as such:

{{ Form::checkbox('shipment_billing_status', '2', $shipment->shipment_billing_status) }}
{{ Form::checkbox('shipment_billing_status', '3', $shipment->shipment_billing_status) }}

Both fields are named and go into "shipment_billing_status" in my database, the default values are 2 and 3. But I'm not sure how to get the old value from my database.

At the moment, they both appear checked, but given that my "shipment_billing_status" field is equal to 1, neither should be checked at this time.

How can I fix this issue?

There are 4 arguments you can pass to Form::checkbox, the 3rd one being true or false. When you call $shipment->shipment_billing_status it returns whatever value you have in your DB. Since it does not evaluate to false it checks the box. I would put a mutator on your model like so:

public function getCheckboxShipmentBillingStatusAttribute(){
    $bool = ($this->shipment_billing_status == 3)? true : false;
    return $bool;
}

Then call this instead of $shipment->shipment_billing_status

{{ Form::checkbox('shipment_billing_status', '2', $shipment->checkbox_shipment_billing_status) }}

which will return true and check the box if it is equal to 3, or false which will display as unchecked for anything else. Form model binding expects that the field will be stored in the DB as true or false and not dependent on 1 or 2 or 3. So other than mutating the values there is no easy way to implement your number system into it.

For the documentation see https://laravel.com/docs/5.5/eloquent-mutators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM