views:

651

answers:

1

Hi Guys,

Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.

The one example i have of this in cake i found at - http://www.mail-archive.com/[email protected]/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)

I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).

I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.

Thanks in advance

+4  A: 

I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.

Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:

<input type="text" name="data[User][field][0]" />

Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.

    $(document).ready( function() {
      $("#link_id").click( 'add_field' );
      var field_count = 1;
    } );

    function add_field()
    {
      var f = $("#div_addfield");
      f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
      field_count++;
    }

Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.

Travis Leleu
Perfect, i did consider just doing that but wanted to see if there was a more cake-centric way of doing it, Cheers
kwhohasamullet