It's not really that hard. You would want to create form elements that use the #tree
attribute, to make sure the data for instances of EntityB will be well structured.
In order to make add another functionality you need to:
Keep track of the count in the $form_state
.
if (empty($form_state['count'])) {
$form_state['count'] = 2;
}
Add a button somewhere to add another.
$form['entity_b']['add_another'] = array(
'#type' => 'submit',
'#value' => t('Add another'),
'#limit_validation_errors' => array(),
'#submit' => array('add_another_submit_handler'),
);
function add_another_submit_handler(&$form, &$form_state) {
// Add one to our counter and rebuild the form
$form_state['count'] += 1;
$form_state['rebuild'] = TRUE;
}
The above will work with no JavaScript. If you want to Ajax-enable it, you need to do some work on the wrapper.
Add a CSS ID that is used from the Ajax callback.
$form['entity_b'] = array(
'#tree' => TRUE,
'#attributes' => array('id' => array('add-another')),
// ...
);
Add the #ajax
element.
// ...
'#ajax' => array(
'callback' => 'add_another_ajax',
'wrapper' => 'add-another',
'effect' => 'fade',
),
// ...
Add the Ajax callback function.
function add_another_ajax($form, &$form_state) {
return $form['entity_b'];
}