Skip to content

Commit fad0701

Browse files
authored
Merge pull request #163 from yajra/multiple-form-values
Add postAjaxWithForm, fix multiple form values for select and checkbox
2 parents 7f33954 + ee2f429 commit fad0701

File tree

2 files changed

+45
-8
lines changed

2 files changed

+45
-8
lines changed

src/Html/Options/HasAjax.php

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,46 @@ public function ajax(array|string $attributes = ''): static
4444
return $this;
4545
}
4646

47+
/**
48+
* @param string $url
49+
* @param string $formSelector
50+
* @return $this
51+
*/
52+
public function postAjaxWithForm(string $url, string $formSelector): static
53+
{
54+
$attributes = ['url' => $url];
55+
56+
Arr::set($attributes, 'type', 'POST');
57+
Arr::set($attributes, 'headers.X-HTTP-Method-Override', 'GET');
58+
59+
$script = $this->getScriptWithFormSelector($formSelector);
60+
61+
$attributes['data'] = "function(data) { $script }";
62+
63+
return $this->ajax($attributes);
64+
}
65+
66+
/**
67+
* @param string $formSelector
68+
* @return string
69+
*/
70+
protected function getScriptWithFormSelector(string $formSelector): string
71+
{
72+
return <<<CDATA
73+
var formData = _.groupBy($("$formSelector").find("input, select").serializeArray(), function(d) { return d.name; } );
74+
$.each(formData, function(i, group){
75+
if (group.length > 1) {
76+
data[group[0].name] = [];
77+
$.each(group, function(i, obj) {
78+
data[obj.name].push(obj.value)
79+
})
80+
} else {
81+
data[group[0].name] = group[0].value;
82+
}
83+
});
84+
CDATA;
85+
}
86+
4787
/**
4888
* Setup ajax parameter for datatables pipeline plugin.
4989
*
@@ -80,14 +120,7 @@ public function getAjaxUrl(): string
80120
*/
81121
public function ajaxWithForm(string $url, string $formSelector): static
82122
{
83-
$script = <<<CDATA
84-
var formData = $("$formSelector").find("input, select").serializeArray();
85-
$.each(formData, function(i, obj){
86-
data[obj.name] = obj.value;
87-
});
88-
CDATA;
89-
90-
return $this->minifiedAjax($url, $script);
123+
return $this->minifiedAjax($url, $this->getScriptWithFormSelector($formSelector));
91124
}
92125

93126
/**

tests/BuilderOptionsTest.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,10 @@ public function it_has_ajax_options()
141141
$this->assertStringContainsString('custom_script', $builder->getAjax('data'));
142142
$this->assertStringContainsString("data.id = 123", $builder->getAjax('data'));
143143
$this->assertStringContainsString("data.name = 'yajra'", $builder->getAjax('data'));
144+
145+
$builder->postAjaxWithForm('/test', '#formId');
146+
$this->assertStringContainsString('find("input, select").serializeArray()', $builder->getAjax()['data']);
147+
$this->assertStringContainsString('#formId', $builder->getAjax('data'));
144148
}
145149

146150
/** @test */

0 commit comments

Comments
 (0)