0

I have a custom entity type, and I'm defining its form, which extends ContentEntityForm. During my save() function, I want the form to conditionally unset fields based on the values of other fields. (example: unset the value of a list select field if a certain checkbox is checked off)

I can't seem to accomplish this with $form_state->setValue() or $form_state->setValueForElement(), in both cases my code is seemingly ignored and the select widget is not unset upon finishing saving (although a var_dump of $form_state->getValues() at the end of the function shows that the values array is indeed being modified the way I want it to be).

However, the following code seems to work nicely for the title field (defined via baseFieldDefinitions(), is not inside a field collection):

$entity = $this->getEntity();
    $entity->set('title', array(array("value" => "aaaaaaaa")));
$entity->save();

My title for the newly saved entity does indeed show up as "aaaaaaaa"

Is it possible to target fields inside field collections in this way using this $entity object? Or is this the totally wrong approach?

1 Answer 1

1

It's not really clear to me why you don't change the values on the entity, but save() is too late.

The entity is built in buildEntity()/copyFormValuesToEntity(), if you want to change how it is build based on form_state values, you have to change them by overriding those methods and doing your changes first.

1
  • Modifying the values via form_state whether during validation or save has been going totally ignored. Modifying at the entity level during save was the only approach that actually did anything. Debugging copyFormValuesToEntity() showed that all of my fields defined via the drupal interface were having !isset($extracted[$name]) evaluate to false (while hidden fields like 'changed' and 'created' do not do this), and I can't figure out why this is the case. I got to debugging extractFormValues, which led me to a dead end.
    – saramm1
    Commented Aug 4, 2016 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.