In a node edit form, I am trying to add items to a multivalue field with unlimited cardinality in a form builder hook, like form_alter or after_build. I can't figure out how to do it, though, at least not very well. For instance, if I fill in the default blank item in form_alter and then add a new blank item, when you click the "Add another item" button, the form resets the items_count for the field to the original entity item count. It doesn't "see" the new blank item I added to the field, so visibly it ends up doing nothing. There's also strange results on Submit if there's a validation error.
Is there a way to do this? Not in response to clicking on a button, so not in a submit function. I think that may be the problem. That items count is in the form state storage, and from what I've seen searching around, trying to change form state in a form builder function doesn't work. I may be misunderstanding that, though.
For context, the task I'm trying to accomplish is that I have two related fields. One is an entity reference, one is an unlimited text field. A value from the referenced entity needs to always be one of the values in the unlimited text field. So when I build the form, I need to add that value to the list if it isn't there, and still end up with a blank item at the bottom of the list.