diff --git a/README.md b/README.md index 5562eaf..d7b55a3 100644 --- a/README.md +++ b/README.md @@ -224,9 +224,9 @@ To store responses to custom fields, just call `saveCustomFields()` and pass in The `saveCustomFields` function can take in a Request or array. ```php -$surveyResponse->saveCustomFields([' - -']); +$surveyResponse->saveCustomFields([ + 'Key' => 'Value' +]); ``` If you're submitting a form request, you can easily: @@ -236,6 +236,21 @@ Use App\... $surveyResponse->saveCustomFields($request->input); ``` +### Making then saving +If you would like to make the custom fields without saving them immediately, you can call +```php +$surveyResponse->makeCustomFields([ + 'Key' => 'Value' +]); +``` + +and then to save you need to call +```php +$surveyResponse->saveCustomFields(); +``` + +This will set the `model_id` for you before saving the CustomField. + ## Querying responses 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). diff --git a/src/Traits/HasCustomFieldResponses.php b/src/Traits/HasCustomFieldResponses.php index 3e11fa0..5b12c24 100644 --- a/src/Traits/HasCustomFieldResponses.php +++ b/src/Traits/HasCustomFieldResponses.php @@ -18,11 +18,29 @@ public function customFieldResponses() } /** - * Save the given custom fields to the model. + * Save the custom fields to the model. + * This parameter accepts a list of fields for immediate saving & backwards compatibility. * * @param $fields */ - public function saveCustomFields($fields) + public function saveCustomFields($fields = []) + { + if (!empty($fields)) { + $this->makeCustomFields($fields); + } + + $this->customFieldResponses->each(function(CustomFieldResponse $field) { + $field->model_id ??= $this->id; // set the ID now, if model did not exist when makeCustomFields() was called + $field->save(); + }); + } + + /** + * Make the given custom fields but do not save. + * + * @param $fields + */ + public function makeCustomFields($fields) { foreach ($fields as $key => $value) { $customField = CustomField::find((int) $key); @@ -38,7 +56,7 @@ public function saveCustomFields($fields) 'model_type' => get_class($this), ]); - $customFieldResponse->save(); + $this->customFieldResponses->push($customFieldResponse); } }