简体   繁体   中英

how to create form elements with custom name in cakephp?

I am working on existing project. There are many forms like this:

<?php echo $form->create('MyForm', array('id' => 'MyFormId')); ?>

  <?php echo $form->input('User.0.username', array( 'label' => false, )); ?>
  <?php echo $form->input('User.0.location', array( 'label' => false, )); ?>

<?php echo $form->end(); ?>

It is generating form elements like this:

<input type="text" id="User0Username" name="data[User][0][username]">
<input type="text" id="User0Location" name="data[User][0][location]">

Bu I want them to be look like this:

<input type="text" id="User0Username" name="User_0_username">
<input type="text" id="User0Location" name="User_0_location">

Is there any $form->create(); function option to get this html instead of changing my forms elements?

Thanks

The Form helper is pretty smart. Whenever you specify a field name with the form helper methods, it'll automatically use the current model name to build an input with a format like the following:

    <input type="text" id="ModelnameFieldname" name="data[Modelname][fieldname]">

You can manually specify the model name by passing in Modelname.fieldname as the first parameter.

echo $this->Form->input('Modelname.fieldname');

If you need to specify multiple fields using the same field name, thus creating an array that can be saved in one shot with saveAll(), use the following convention:

<?php
echo $this->Form->input('Modelname.0.fieldname');
echo $this->Form->input('Modelname.1.fieldname');
?>

<input type="text" id="Modelname0Fieldname" name="data[Modelname][0][fieldname]">
<input type="text" id="Modelname1Fieldname" name="data[Modelname][1][fieldname]">

I always use the bracket version - even for jquery ajax submit. this way it works, by the way:

var ids = new Array();
var myCheckboxes = new Array();
$("#ProductCalculation input:checked").each(function() {
    ids.push($(this).val());
});
...
$.ajax({
    dataType: 'json',
    type: "post",
    data: {
        'data[Product][product_calculation_id]': ids, 
        'data[Product][brand_id]': brands, 
        'data[Category][Category]': categories, 
        'data[Form][connect]': c
    },
    url: targeturl,
    beforeSend: function(xhr) {
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    },
    success: function(html) {
        ...
    }
});

you can manually grab the form elements. not ideal, but it does not break cake-styled coding

i am also sure one could write a jquery plugin to make this automatically in some way. that is actually quite an interesting thing to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM