Hi all!
I've been doing a lot of searching for a solution to this problem, but I'm not finding any solutions; people seem to just give up and/or find workarounds that are suitable for them. However, I'm hoping there's a more elegant way of solving this.
The problem is I have a two related tables in my db: a customer("name")
and an address("street", "'street2", "street3", "city", "county", "postcode", "country_id")
table. Obviously the customer references the address id when it pulls the data.
I have created a single form that has the fields for the customer, and I have included the fields for the address as follows:
class CustomerForm extends Form
{
public function initialize($entity = null, $options = null)
{
if ($options['edit'] === true)
{
$this->add(new Hidden('id'));
$params = [];
}
else
{
$params = [];
}
$field = new Text('name', array_merge($params, [
'class' => 'form-control',
'required' => 'required',
'placeholder' => '{customer_name}'
]));
$field->setLabel('{customer_name}');
$this->add($field);
...
$pre = 'Address.';
for ($i=1; $i < 4; $i++) {
$field = new Text($pre . 'street_' . $i, array_merge($params, [
'class' => 'form-control',
'required' => (($i === 1) ? 'required' : ''),
'placeholder' => '{address} '. $i
]));
$field->setLabel('{address}' . $i);
$this->add($field);
}
$field = new Text($pre . 'city', array_merge($params, [
'class' => 'form-control',
'required' => 'required',
'placeholder' => '{city}'
]));
$field->setLabel('{city}');
$this->add($field);
$field = new Text($pre . 'county', array_merge($params, [
'class' => 'form-control',
'required' => 'required',
'placeholder' => '{county}'
]));
$field->setLabel('{county}');
$this->add($field);
$field = new Text($pre . 'postcode', array_merge($params, [
'class' => 'form-control',
'required' => 'required',
'placeholder' => '{postcode}'
]));
$field->setLabel('{postcode}');
$this->add($field);
$field = new Select($pre . 'country_id', Countries::find(array("order" => "printable_name")), array_merge($params, [
'class' => 'form-control select2',
'required' => 'required',
'useEmpty' => true,
'emptyText' => '{please_select}',
'using' => ['id', 'printable_name']
]));
$field->setLabel('{country}');
$this->add($field);
}
Now if in my controller I use:
$customer = Customers::findFirstById($id);
$form = new CustomersForm($customer, ['edit' => true]);
It will populate the fields from the root customer table, but I'm having issues populating the fields for the related table Addresses.
Does anyone have any bright ideas? Is this even possible?
I've used the $this->tag->setDefault()
method previuosly, but i'm trying to keep away from having to write out every tag every time. I've also considered nesting the forms within each other, but I've been unable to do this.
Any help would be greatly appreciated.