Question

I have a form in the admin section that has a phone numbers dropdown. This dropdown is pulling its values from a phone number table. I added a 'Select--' to the first option of the dropdown so the field is optional and the admin does not have to select a phone number. The issue is when saving this form its saving it to a table that has a foreign key to the phone numbers table. It is complaining when the 'Select--' option is chosen that a constraint is being violated. This field in the database in nullable. So I tried setting the value to null, but its still complaining. This is the code for the dropdown

$alloptions = [];
    $alloptions[] = ["value" => null, "label" => __('Select--')];
    foreach ($tableData as $option) {
        $alloptions[] = ["value" => $option['id'], "label" => __($option['area_code']) . __($option['phone_number'])];
    }

    $this->options = $alloptions;

    return $this->options;

This is the error I am getting

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tablename`, CONSTRAINT `FK_D911C644707AC9D3D31C6B88FC337282` FOREIGN KEY (`phone_number_id`) 

What is the best way to go about keeping the relationship constraint but still allowing for it to be optional to the admin?

Était-ce utile?

La solution

I figured out my solution and posting here if it can help someone in the future. The default value was being set to an empty string in the Database schema file. This was being converted in the Database to default value of 0. This was causing that when I was sending the null selected value from the dropdown it was being converted to 0, which has no relationship mapping in the phone numbers table. I therefore set the default value to NULL instead of empty string and now I am not getting the relationship error!

Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange
scroll top