Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions

Ajax form call and save a many_many relation


Reply

2 Posts   352 Views

Avatar
m-phil

12 March 2014 at 11:37pm (Last edited: 20 March 2014 2:05am), Community Member, 37 Posts

Hey there,
[SS3] I want to refactore my form action method... but got a problem with the $form parameter using ajax.
It works with parameter $data only and then using $db = DB::query('INSERT' or 'UPDATE'); but now I need to update a many_many table ("campaign_campaignphases") and don't want to create all SQL queries manually.

jQuery ajax call:

$('form[data-async] .btn-primary').on('click', function(event) {
var form = $(this).closest('form');
// Get the specific action i.e. SaveCampaign
var action = $(this).attr('name').split('action_')[1];

$.ajax({
type: form.attr('method'),
url: action,
data: form.serialize(),
success: function(response, status) {
// doing some...
}
});

and the action itself in CampaignHolderPage.php should update a Campaign DataObject with

private static $many_many = array(
'CampaignPhases' => 'CampaignPhase'
);

public function SaveCampaign($data, $form) {
// Existing or new entry
$dbId = CampaignHolderPage::decryptId($data['ID']);
if ($data['ID'] != '' && $object = DataObject::get_by_id('Campaign', $dbId)) {
$form->saveInto($object);
$object->write();

// Phases
$selectedElements = $data['CampaignPhases'];
foreach($selectedElements as $selectedElement => $selectedId) {
$reference = DataObject::get_by_id('CampaignPhase', $selectedId);
$object->CampaignPhases()->add($reference);
unset($reference);
}
...
} else {
// Update...
$object = new Campaign();
$form->saveInto($object);
$object->write();
...
}
...

Request error:
ERROR [Warning]: Missing argument 2 for CampaignHolderPage_Controller::SaveCampaign()

Thx for any ideas or helping links

Avatar
m-phil

13 March 2014 at 7:36am Community Member, 37 Posts

My question is: How can I get $form->saveInto() work via ajax?