问题
I have two entities involved in this issue. A user can have an event that has multiple pieces of equipment tied to it. I need a form that the user can enter hours and roi for that piece of equipment at that particular event. Equipment in this case is actually an entity in the middle of two other entities (equipment and event) to create a many to many with extra parameters. So equipment has the fields 'hours' and 'roi'. I would like to have my form dynamically added a field for hours and roi for each piece of equipment on the event. I can get up to this part. The part I have issues, is adding the elements to the form. A page that I've been looking at to try and help me: Zend_Form - Array based elements?.
However, in that question, they don't seem to be doing the same thing I wish to do.
Here's what I have right now:
foreach ($event['equipment'] as $equipment)
{
$form->addElement('text', 'roi', array(
'label' => $equipment['equipment']['model'] . ' ROI',
'required' => true,
'belongsTo' => strval($equipment['id'])
));
$form->addElement('text', 'hours', array(
'label' => $equipment['equipment']['model'] . ' Hours',
'required' => true,
'belongsTo' => strval($equipment['id'])
));
}
However, with this method, only the last piece of equipment's information is shown. If there's a way to set this up that I'm not thinking of, please let me know. I just need to be able to parse through an array of data at the end and I'll be able to take it from there.
Thanks for your help in advance.
回答1:
You are adding the same element every loop pass. The second parameter to addElement
is the element identifier (roi
and hours
in your case).
A possible alternative could be the following:
foreach ($event['equipment'] as $equipment)
{
$form->addElement('text', 'roi' . $equipment['id'] , array(
'label' => $equipment['equipment']['model'] . ' ROI',
'required' => true,
'belongsTo' => strval($equipment['id'])
));
$form->addElement('text', 'hours' . $equipment['id'], array(
'label' => $equipment['equipment']['model'] . ' Hours',
'required' => true,
'belongsTo' => strval($equipment['id'])
));
}
(by appending the ID to each element name/identifier).
There could be other solutions, but you always need to have unique identifiers for each element you add to the form.
Hope that helps,
来源:https://stackoverflow.com/questions/7459281/zend-form-array-based-element-setup-and-retreival