I'm trying to use the following partial and jQuery to allow the user to add/update/delete service records. I have an "Add service button" that's bound to a jquery function that basically retrieves the partial and appends a new set of service record fields to the existing service(s) listing.
//Jquery function to add existing rows
$(document).on('click','#add_service', function(e){
if (service_count > max_services)
{
alert('The maximum number of service records for this person has been reached');
}
else
{
$.get("/service_fields", function( result ) {
// result contains whatever that request returned
service_count++;
$('#service_field').append(result);
}, 'html'); // or 'text', 'xml', 'more'
}
e.preventDefault();
});
Services field (partial):
Service Date
<input type="text" name="service[][service_date]" >
Service Provided <select name="service[][service_categorytype_id]" >
<option value="1">Mentoring</option>
<option value="2">Personal Counseling</option>
</select>
Comment <textarea name="][comment]" ></textarea>
<input type="button" name="delete_button" value="Delete Service" >
</div>
The problem is when it comes to editing the record with the addition of a new service record. Without an index value ($service-id) each field would end up as a separate array, similar to what's displayed below. What would be the best way to handle this? One thought i had was to give each record an incrementing index array value [0,1,2,3] and having a hidden field that contains the $service->id to use to update existing records, but I don't know if I'm over complicating things. Thanks
Array
(
[3] => Array
(
[service_date] => 02/06/2017
[service_category_id] => 1
[comment] => Referred to another program to help me out or something
)
[4] => Array
(
[service_date] => 02/02/2017
[service_category_id] => 3
[comment] => This record preceeds the other service
)
[5] => Array
(
[service_date] => 12/22/2016
[service_category_id] => 7
[comment] => Another record
)
[6] => Array
(
[service_date] => 03/01/2017
)
[7] => Array
(
[service_category_id] => 10
)
[8] => Array
(
[comment] => Yet another record
)
)
via WillieG