This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Hi
I have an error when I try to create a record from a builder form. I explain the situation:
I have two tables, with their fields:
-Person: id, name, address, telephone
-Volunteer: id, person_id, position
What I need is for the new volunteer form to have the fields of name, address, telephone and position, and when creating first the registration is created in person, and then in voluntary.
Currently in the Volunteer model I have put:
public $ belongsTo = [
'person' => ['Muadek \ Biosbardos \ Models \ Person', 'key' => 'person_id', 'otherKey' => 'id']
];
In the volunteer fields.yaml, the following:
fields:
'person [dni]':
label: ID
span: auto
type: text
'person [name]':
label: Name
span: auto
type: text
'person [address]':
label: Address
span: auto
type: text
'person [phone]':
label: Telephone
span: auto
type: text
position:
label: Position
span: auto
type: text
If I want to see a record, it leaves me perfectly, even modifying it, the problem is when I want to create a new one, which gives me the error "Call to a member function hasRelation () on null"
Am I missing something to fill out?
P.D: Sorry for not knowing how to handle the markdown syntax, my poor English and the long text for the question
Last updated
Welcome to the advanced stages of using October CMS! In essence, what happens here is the relationship is not initialized upon creation. You may add the following code to your controller to ensure the relationship has an empty model that can be used to assign values
public function formExtendModel($model)
{
if ($this->formGetContext() === 'create' && !$model->person) {
$model->person = new \Muadek\Biosbardos\Models\Person;
}
return $model;
}
The formExtendModel
method in the controller will hook in to the form behavior and extend the model.
When the form context is creation mode, $this->formGetContext() === 'create'
, and we detect there is no relationship already initialized, !$model->person
.
We then initialize the model on the parent Volunteer relationship, $model->person = new Phone;
Now the creation of both models should be successful
Hope this helps
Last updated
Hi
The code works correctly.
Thank you very much, the truth is that I had been looking for information for a while and I couldn't find what I was missing.
1-3 of 3