Hi,

I need a help from Drupal guru with deep understanding of Drupal forms and forms processing.
I'd like to build a form that can change itself by adding or removing fields, as a reaction on the appropriate buttons and then catch all the fields data in _submit function.
Let me illustrate the task with the code below. It is a managing system of the spy store, where operator can add and remove orders of the clients and store results in the DB.


// get the data array (see function code below)
$data = get_data();

// build the form dynamically according to the $data array
$form['client'] = array('#type' => 'textfield','#title' => t('Client'),'#default_value'=> $data['client'],'#tree' => true,);
$form['orders'] = array('#type' => 'fieldset',	'#title' => t('Orders'), '#tree' => true,);
foreach ($data['orders'] as $order_id => $order_description) {
	$form['orders'][$order_id] = array('#type' => 'textfield','#title' => t('Order '.$order_id),'#default_value'=>$order_description,);
}

// first two options should modify the form
$form['add_order'] = array('#type' => 'button', '#name' => 'op', '#value' => t('Add order'));
$form['delete_order'] = array('#type' => 'button', '#name' => 'op', '#value' => t('Delete order'));
$form['submit']   = array('#type' => 'submit', '#name' => 'op', '#value' => t('Save'));

$output = drupal_get_form('client_form', $form);
return  $output;


....

function get_data(){
	// get data from DB & return:
	return array('client'=>'Mr. Bond', 'orders'=>array(0=>'watch',1=>'knife'));
}

function client_form_submit($form_id, $form_values){
       // store updated order list to the database;
}

How this functionality may be implemented?
Thank you in advance,
Jacob.

Comments

Jacob’s picture

I found solution myself. The idea is to catch $form_data on the _submit() stage , make required modifications to the $form_data array (removing or adding orders), saving output in $_SESSION variable and redirecting page to itself.
get_data() function should check if $_SESSION variable is set and return it. Form will be rendered according to the updated data set and displayed accordingly. Don't forget to unset $_SESSION variable after saving results in _submit() function.
If anyone needs the solution details, feel free to contact me

Regards,
Jacob.

SoftDux’s picture

Can you please share in more depth exactly how you made it work, maybe with some sample code?