If you need to save two models using a form controller, you may run into some issues. However, it is possible! The key is to instantiate the related models manually.
Assume you have a Person model and a Phone model. On your People form controller you want to create/update the Phone model, but you don't want it to look like it's a separate record. Proxy fields to the rescue!
#Acme/Anvil/Models/Person/fields.yaml
fields:
name:
label: Name
commentAbove: Text field, required. Given name in the first box, preferred name in the second box.
# Proxy Fields
phone[name]:
span: auto
label: Phone Name
phone[number]:
span: auto
label: Phone Number
Shown above are two proxy fields which are denoted by the nested keys. Note that phone[] is the name of the relation on the Person model.
Once your proxy fields are defined, there's just one more important step: manually instantiating the related model.
//Acme/Anvil/Controllers/People.php
...
public function formExtendModel($model)
{
/*
* Init proxy field model if we are creating the model
*/
if ($this->action == 'create') {
$model->phone = new Phone;
}
return $model;
}
...
And viola! You can now save data on multiple models at a time. Note that this only works for a single related model (1 phone to 1 person), for more than one, use a Relation behavior.
See also: the People controller of the October Test Plugin
