Skip to content

Commit 77e93aa

Browse files
committed
ADDED: Ability to makeCustomFields() and then call saveCustomFields() to commit the data at a later point in time.
1 parent 92b7de2 commit 77e93aa

File tree

2 files changed

+39
-6
lines changed

2 files changed

+39
-6
lines changed

README.md

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,9 +224,9 @@ To store responses to custom fields, just call `saveCustomFields()` and pass in
224224
The `saveCustomFields` function can take in a Request or array.
225225

226226
```php
227-
$surveyResponse->saveCustomFields(['
228-
229-
']);
227+
$surveyResponse->saveCustomFields([
228+
'Key' => 'Value'
229+
]);
230230
```
231231

232232
If you're submitting a form request, you can easily:
@@ -236,6 +236,21 @@ Use App\...
236236
$surveyResponse->saveCustomFields($request->input);
237237
```
238238

239+
### Making then saving
240+
If you would like to make the custom fields without saving them immediately, you can call
241+
```php
242+
$surveyResponse->makeCustomFields([
243+
'Key' => 'Value'
244+
]);
245+
```
246+
247+
and then to save you need to call
248+
```php
249+
$surveyResponse->saveCustomFields();
250+
```
251+
252+
This will set the `model_id` for you before saving the CustomField.
253+
239254
## Querying responses
240255

241256
You can query for responses on any field by using the `WhereCustomField()` scope. The function takes in the field object and the value you're looking for. To learn more about query scopes visit [this link](https://laravel.com/docs/6.x/eloquent#query-scopes).

src/Traits/HasCustomFieldResponses.php

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,29 @@ public function customFieldResponses()
1818
}
1919

2020
/**
21-
* Save the given custom fields to the model.
21+
* Save the custom fields to the model.
22+
* This parameter accepts a list of fields for immediate saving & backwards compatibility.
2223
*
2324
* @param $fields
2425
*/
25-
public function saveCustomFields($fields)
26+
public function saveCustomFields($fields = [])
27+
{
28+
if (!empty($fields)) {
29+
$this->makeCustomFields($fields);
30+
}
31+
32+
$this->customFieldResponses->each(function(CustomFieldResponse $field) {
33+
$field->model_id ??= $this->id; // set the ID now, if model did not exist when makeCustomFields() was called
34+
$field->save();
35+
});
36+
}
37+
38+
/**
39+
* Make the given custom fields but do not save.
40+
*
41+
* @param $fields
42+
*/
43+
public function makeCustomFields($fields)
2644
{
2745
foreach ($fields as $key => $value) {
2846
$customField = CustomField::find((int) $key);
@@ -38,7 +56,7 @@ public function saveCustomFields($fields)
3856
'model_type' => get_class($this),
3957
]);
4058

41-
$customFieldResponse->save();
59+
$this->customFieldResponses->push($customFieldResponse);
4260
}
4361
}
4462

0 commit comments

Comments
 (0)