Search code examples
iosswifteureka-forms

How to create an Eureka AlertRow with options from Core Data and a "None" option?


GTDItemEntity is a Core Data entity. I need to be able to take "None" or "No Project" as a valid value. I can do that with .value and .displayValueFor. But how do I allow it in the options?

 <<< AlertRow<GTDItemEntity>() {
            $0.title = "Project"
            $0.value = self.item?.project
            $0.displayValueFor = { project in
                return project?.text ?? "No Project"
            }
            $0.options = [nil] // sample one option with nil value
            $0.onChange() {
                self.item.project = $0.value
            }
        }

Solution

  • One way to do this is to change to a AlertRow<GTDItemEntity?>:

     <<< AlertRow<GTDItemEntity>() {
                $0.title = "Project"
                $0.value = self.item?.project
                $0.displayValueFor = { project in
                    return project??.text ?? "No Project" // *
                }
                $0.options = [nil] // sample one option with nil value
                $0.onChange() {
                    self.item.project = $0.value ?? nil // *
                }
            }
    

    Note that this makes $0.value a double optional, which is why I changed some code in the lines marked with *.

    Another way to do this would be to add a special GTDItemEntity as one of the options. You would assign a value to a certain field of this special GTDItemEntity such that no other GTDItemEntity has that value. Then, you can check if the value of the row has changed to that special entity in onChange. If it did, set the value to nil.