php - building dynamic form in cakephp

787

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.

829

Answer

Solution:

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.

People are also looking for solutions to the problem: php - Search query doesn't return desired results

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.