如果用户不想添加hasMany FormItems,如何提交表单

时间:2019-01-04 12:41:51

标签: laravel validation laravel-5.7

我正在使用Laravel 5.7.*

我有form,其中有很多formItems,就像form hasMany formItemsformItems belongsTo form,但我希望它们之间有一个if,如果用户不想要仅在formItems中添加formDB数据存储,并且如果用户想在formItems中添加DB两个数据存储,现在,它存储两个数据在DB中,但是如果用户不希望使用formItems,我不会如何存储它。

这是我的FormController store method()

public function store(Request $request)
{
    //SUBMITTING FORM DATA
    $form = Form::create([
        'user_phone' => $request['user_phone'],
        'user_name' => $request['user_name'],
    ]);

    //SUBMITTING FORMITEMS DATA
    $form_items = [];
    foreach($request['formItems'] as $form_item) {
        $form_items[] = new FormItem([
            'form_id' => $form->id,
            'family_name' => $form_item ['family_name'],
            'family_phone' => $form_item ['family_phone'],
        ]);
    }
    $form->formItems()->saveMany($form_items);
}

便于更好理解的图像enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以在表单上有一个复选框,询问用户是否也要保存表单项。

merge(source1$, source2$).pipe(take(1))

,然后在您的控制器中,您可以执行以下操作:

<input type="checkbox" name="save-form-items" value="true" id="save-form-items">
<label for="save-form-items"> Do you want to save form items?</label>

答案 1 :(得分:0)

您可以做到

public function store(Request $request)
{
   //SUBMITTING FORM DATA
   $form = Form::create([
       'user_phone' => $request['user_phone'],
       'user_name' => $request['user_name'],
    ]);


    $form_items = [];
    foreach($request['formItems'] as $form_item) {
      // when the user enter $form_item ['family_name'] && $form_item ['family_phone'] store the FormItem
      // or $form_item ['family_name'] || $form_item ['family_phone']
      // depending if both are required or not 
      if($form_item ['family_name'] && $form_item ['family_phone']){
        $form_items[] = new FormItem([
            'form_id' => $form->id,
            'family_name' => $form_item ['family_name'],
            'family_phone' => $form_item ['family_phone'],
        ]);
      }
    }

    $form->formItems()->saveMany($form_items);

}