dongnao9525 2010-02-10 16:19
浏览 61

在cakephp中构建动态表单

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条回答 默认 最新

  • dongyijing2353 2010-02-14 07:08
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分