Reputation: 57
I am new to Laravel and trying to get my head around how to allow a user to repeat a field.
I have a form that allows a user to create a basic page which has a title and description, I'd like to allow the user to then if they choose create another title and description field using a "Add more" button.
They allow them to re-order these field collections.
Cheers, Chris
Upvotes: 2
Views: 2631
Reputation: 846
This seems to be less about Laravel and more about general DB Schema, PHP and UI practices. So due to the broad spectrum of answers this requires, I will answer mostly using best practice concepts to avoid being overly wordy (using Laravel for context).
Front-end
For the ability to add another set of fields on the fly, you will want to use a form array:
<div class="field-set">
{{ Form::text('fields[0]["title"]', Input::old('fields[0]["title"]')) }}
{{ Form::textarea('fields[0]["description"]', Input::old('fields[0]["description"]')) }}
</div>
<a href="#" class="add-more-link">+ Add more</a>
Your 'add-more-link' should have a javascript trigger that will duplicate and append the 'field-set' element with an iteration of the index in the form array
(e.g. fields[1]["title"], fields[2]["title"])
Note: You can do this without JS, but you will have to repost the page with some parameter that increments the amount of fields to create and then loop through that many times while rendering the field sets on DOM generation.
To allow for reordering, I recommend jQuery UI's Sortable. Note: You can accomplish this without JS too by POSTing up or down increments for each field set, but more processing would need to occur in the back-end.
Back-end
In the model where you handle the save, grabbing the data via Input::get('fields') will store it into a PHP array that you can iterate through to validate, parse and store the data.
As for your DB schema, you will need to account for the creation of any number of new fields. This means that will likely need a separate table that will be joined on users. (Columns: id, user_id, title, description)
In Laravel you can define a Has Many Relationship on the users model that will grab all the titles and descriptions for any given user. http://laravel.com/docs/eloquent#relationships
Upvotes: 6
Reputation: 15653
I'm not sure you are using forms correctly, although its a little hard to tell from you question.
If you want to create a new resource (with a title and description) you dont add new form fields. You can have an 'add more' button, but this button just spawns another instance of your form which can then be posted.
But to be honest, you question is so vaugue its hard to tell what your problem is...
Upvotes: 0