Set multiple entities in Symfony based on values

Viewed 61

I am trying to set multiple entities depending on if the values exist or not.

if ($guestMinorCheckout === 'Yes') {
    $optionInfo = 'adult-authorized';
    $value = 'yes|';
    foreach ($guestMinorCheckout as $guestInfo) {
        if (!is_null($guestContactCheckInOutPhone)) {
            $option = new EventAttendeeOption();
            $option->setOption('adult-authorized-sms');
            $option->setValue($guestContactCheckInOutPhone);

        }
        if (!is_null($guestContactCheckInOutEmail)) {
            $option = new EventAttendeeOption();
            $option->setOption('adult-authorized-email');
            $option->setValue($guestContactCheckInOutEmail);
        }
    }
}

this code above doesn't work but its what I am trying to accomplish.

I am getting this data from an API call, therefore the values may or may not exist. if they do exits id like to set to those values.

1 Answers

Not sure exactly where you get $guestContactCheckInOutPhone and $guestContactCheckInOutPhone. I assume they are in some data array you said you get from the API. Hopefully it's a key, value array with the keys are the same as the field names. If that's the case, instead of checking if each field is in the array you can use a reflection class:

$option = new EventAttendeeOption();
$reflectionClass = new \ReflectionClass(EventAttendeeOption::class);

foreach ($data as $key => $value) {
    $reflectionClass->getProperty($key)->setValue($option, $value);
}

Edit: On closer inspection I see that besides some minor workflow problems your code should work and my answer is not exactly what you need. Can you share why it's not working?

Related