Jump to:

3429 Posts in 1057 Topics by 734 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Ajax form call and save a many_many relation

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 296 Views
  • m-phil
    Avatar
    Community Member
    37 Posts

    Ajax form call and save a many_many relation Link to this post

    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

  • m-phil
    Avatar
    Community Member
    37 Posts

    Re: Ajax form call and save a many_many relation Link to this post

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

    296 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.