tags:

views:

514

answers:

1

I'm trying to build a form dynamically based on the field and its definitions stored in a XML file. In my xml, I have defined 1 checkbox with some label and 1 textfield with some label.

How do I build a form dynamically based on what I have in my xml.

I dont want to create any models.

+1  A: 

Not Quite sure where you're going with this or why it's needed. I've built dynamic forms from db definitions, (so that adding/removing fields would have a front end, but don't see why one would do that from an xml file.) Nevetheless, here's the basic idea:

In a Controller function

// Import cake's xml class
App::import('Xml');
// your XML file's location
$f = "/path/to/form.xml"; //no need to fopen('file.xml','r'), cake does it
// parse the xml
$xml_array =& new XML($f);
$this->set('form_info', Set::reverse($xml_array));

In a view:

 //Assuming you know how the xml is gonna be setup declare the magic form elements
e($form->create('Model', array('action'=>'action_name')));
foreach($form_info[fields] as $field){ 
   e($form->input($field['name'], array('class'=>field['class'],
   'label'=>field['label'], 'type'=>$field['type'])
}
//and close the form:
e($form->end('submit'));

Thats the basic idea, in practice I would wrap those array options in !empty() checks, and depending on your xml structure and fields used you'll need to make adjustments to the conditional (perhaps implementing a switch case to handle specific formatting.) This clearly assumes your table or model is set up to handle any of the fields set.

stevenf