php - 商店注册工作不正常(代码总是转到 "if ($validator->passes()) {...}"的其他部分

标签 php laravel

我在 registration.blade.php 页面中有一个表单,供用户输入一些信息以在 session 中进行注册。

在下面的表格中,有一部分使用了 getHtmlInput() 方法,该方法用于为用户选择的每种票证/注册类型显示与该注册类型关联的自定义问题,供用户使用回答。如果在 registration_type_questions 数据透视表中问题的“required”列为“1”,则添加“required”属性。

如果用户在 session 中进行注册并且用户没有选择具有与注册相关的自定义问题的票证/注册类型,则代码输入“if ($validator->passes) ()) {...}”。

问题:

问题是当存在与一种或多种选定票证/注册类型相关联的自定义问题时。

如果需要自定义问题,我也想在 Laravel 中对其进行验证。所以我在 storeRegistration() 中有下面的代码,如果没有回答所需的自定义问题,它会显示消息“填写所有必填字段”。

但即使用户填写了所有必填的自定义问题,代码也永远不会在 if "if ($validator->passes()) {...}"中输入。你知道为什么吗?此外,如果问题是必需的,并且从控制台中的 HTML 中删除了必需的属性,并且用户单击“商店注册”,则不会出现验证错误。

代码总是转到 if ""if ($validator->passes()) {...}"的 else 部分,并显示为 "else{dd ($validator->errors());":

MessageBag {#278 ▼
  #messages: array:1 [▼
    "participant_question.0" => array:1 [▼
      0 => "The participant question.0 field is required."
    ]
  ]
  #format: ":message"
}

你知道问题出在哪里吗?


storeRegistrationInfo() 存储注册信息,并进行验证以检查是否未回答所需的自定义问题:

public function storeRegistration(Request $request, $id, $slug = null, Validator $validator)
    {
        $user = Auth::user();

        $rules = [];
        $messages = [];

        if (isset($request->participant_question_required)) {

            dd($request->participant_question_required);

            $messages = [
                'participant_question.*.required' => 'Fill all mandatory fields',
            ];

            foreach ($request->participant_question_required as $key => $value) {
                $rule = 'string|max:255'; // I think string should come before max

                // if this was required, ie 1, prepend "required|" to the rule
                if ($value) {
                   $rule = 'required|' . $rule;
                }
                $rules["participant_question.{$key}"] = $rule;
            }
        }

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->passes()) {
            dd('test');  // this dont appears
            // create an entry in the registrations table
            // create an entry in the participants table for each registered participant
            // create a entry in the answer table for each answer to a custom question
            if (isset($request->participant_question)) {
                foreach( $request->participant_question as $key => $question ) {
                     $answer = Answer::create([
                         'question_id' => $request->participant_question_id[$key],
                         'participant_id' => $participants[$key]->id,
                          'answer' => $request->participant_question[$key],
                     ]); 
               }
            }
        }
    }

如果数据库中的问题表是这样的:

id      question     conference_id
1        Phone?          1

并且在数据库数据透视表中 registration_type_questions 是:

id  registration_type_id   question_id    required
 1           1                   1             1 

根据上面的数据透视表和问题表的值,使用 getHTMLInput() 生成的 HTML 是:

<form method="post" id="registration_form" action="http://proj.test/conference/1/conference-test/registration/storeRegistration">
    <input type="hidden" name="_token" value="">
    <p> Is not necessary additional info for the registration. Please just answer the following questions. </p>
     <input type="hidden" value="" name="participant_name[]">
     <input type="hidden" value="" name="participant_surname[]">
    <input type="hidden" name="rtypes[]" value="1">
    <div class="form-group">
        <label for="participant_question">Phone?</label>                                           
        <input type="text" name="participant_question" class="form-control" required="">
        <input type="hidden" name="participant_question_required[]" value="1">
        <input type="hidden" value="1" name="participant_question_id[]">
    </div>                                                                  
    <input type="submit" class="btn btn-primary" value="Store Registration">
</form>

生成 html 的方法 getHtmlInput() 在问题模型中:

public function getHtmlInput($name = "", $options = "", $required = false, $class = "", $customtype = false)
{
    $html = '';
    $html .= $customtype == 'checkbox' ? "<div class='checkbox-group ".($required ? " required" : "")."'>" : '';
    $html .= $customtype == 'select_menu' ? "<select name='participant_question' class='form-control' " . ($required ? " required" : "")
        . ">" : '';

    if (empty($options)) {
        switch ($customtype) {
            case "text":

                $html .= " 
                <input type='text' name='participant_question' class='form-control'" . ($required ? " required" : "")
                    . ">";
                break;

            case "file":
                $html .= " 
                <input type='file' name='participant_question' class='form-control'" . ($required ? " required" : "") . ">";
                break;

            case "long_text":
                $html .= "
            <textarea name='participant_question' class='form-control' rows='3'" . ($required ? " required" : "") . ">"
                    . $name .
                    "</textarea>";
                break;
        }
    } else {
        foreach ($options as $option) {
            switch ($customtype) {
                case "checkbox":
                    $html .= " 
        <div class='form-check'>
            <input type='checkbox' name='participant_question[]' value='" . $option->value . "' class='form-check-input' >
                <label class='form-check-label' for='exampleCheck1'>" . $option->value . "</label>
        </div>";
                    break;
                case "radio_btn":
                    $html .= " 
            <div class='form-check'>
                <input type='radio' name='participant_question[]' value='" . $option->value . "' class='form-check-input'" . ($required ? " required" : "") . ">" .
                        '    <label class="form-check-label" for="exampleCheck1">' . $option->value . '</label>' .
                        "</div>";
                    break;
                case "select_menu":
                    $html .= "<option value='" . $option->value . "'>" . $option->value . "</option>";
                    break;
            }
        }
    }
    $html .= $customtype == 'select_menu' ? "</select>" : '';
    $html .= $customtype == 'checkbox' ? "</div>" : '';

    return $html;
}

在 View 中使用 getHtmlInput() 为自定义问题生成 html 的表单:

<div class="card-body">
    @include('includes.errors')
    <form method="post" id="registration_form" action="{{route('conferences.storeRegistration', ['id' => $id, 'slug' => $slug])}}">
        {{csrf_field()}}
        @if (!is_null($allParticipants) && is_int($allParticipants))
           <!-- If all_participants in conferences table is "1"
                is necessary to collect the name and surname of all participants -->
            @if($allParticipants == 1)
                <p>Please fill the following form.</p>
            @else
               <!-- if is 0 is not necessary to collect the name and surname of each participant 
                    and its used the name and surname of the auth user to do the registration-->
              <!-- the registration types selected by the user can have custom questions associated if don't have no 
                    custom question will appear, if 1 or more registration types have custom questions associated they will
                    appear on the form for the user to answer-->
                @if(collect($selectedRtypes)->first()['questions'] == null)
                    <p>Is not necessary additional info for the registration. </p>
                @else
                    <p>Is not necessary additional info for the registration. Please just answer the following
                        questions.</p>
                @endif
            @endif

            <!-- for each selected ticket is necessary collect the name and surname because all_participants is "1" inside this if -->
            @foreach($selectedRtypes as $k => $selectedRtype)
                @foreach(range(1,$selectedRtype['quantity']) as $val)
                    @if($allParticipants == 1)
                        <h6 class="text-heading-blue mb-3 pb-2 font-weight-bold">
                            Participant - {{$val}} - {{$k}}</h6>
                        <div class="form-group font-size-sm">
                            <label for="name{{ $k }}_{{ $val }}"
                                   class="text-gray">Name</label>
                            <input type="text" id="name{{ $k }}_{{ $val }}"
                                   name="participant_name[]" required
                                   class="form-control" value="">
                        </div>
                        <div class="form-group font-size-sm">
                            <label for="surname{{ $k }}_{{ $val }}"
                                   class="text-gray">Surname</label>
                            <input type="text" id="surname{{ $k }}_{{ $val }}"
                                   required class="form-control"
                                   name="participant_surname[]" value="">
                        </div>
                        <!-- for each registration type if there are custom questions thet will appear so the user can answer -->
                        @foreach($selectedRtype['questions'] as $customQuestion)
                            <div class="form-group">
                                <label for="participant_question">{{$customQuestion->question}}</label>
                                <!--if the custom question is a type checkbox, radio button or select menu-->
                                @if($customQuestion->hasOptions() && in_array($customQuestion->type, ['checkbox', 'radio_btn', 'select_menu']))
                                    {!! $customQuestion->getHtmlInput(
                                        $customQuestion->name,
                                        $customQuestion->options,
                                        ($customQuestion->pivot->required == '1'),
                                        'form-control',
                                        $customQuestion->type)
                                    !!}
                                <!-- if the custom question is of type text, file, textarea -->
                                @else
                                    {!! $customQuestion->getHtmlInput(
                                        $customQuestion->name,
                                        [],
                                        ($customQuestion->pivot->required == '1'),
                                        'form-control',
                                        $customQuestion->type)
                                    !!}
                                @endif
                                <input type="hidden"
                                       name="participant_question_required[]"
                                       value="{{ $customQuestion->pivot->required }}">
                                <input type="hidden"
                                       value="{{ $customQuestion->id }}"
                                       name="participant_question_id[]"/>
                            </div>
                        @endforeach
                    @else
                        <input type="hidden" value=""
                               name="participant_name[]"/>
                        <input type="hidden" value=""
                               name="participant_surname[]"/>
                    @endif
                    <input type="hidden" name="rtypes[]"
                           value="{{ $selectedRtype['id'] }}"/>
                @endforeach
                <!-- is not necessary collect info of each participant and its used the name and surname of the auth user
                    to do the registration -->
                @if ($allParticipants == 0)
                    <!-- if the selected registration types have custom questions associated they will appear in the form
                        so the user can answer -->
                    @foreach($selectedRtype['questions'] as $customQuestion)
                        <div class="form-group">
                            <label for="participant_question">{{$customQuestion->question}}</label>
                            <!-- if the custom question is of type checkbox, radio button or select menu -->
                            @if($customQuestion->hasOptions() && in_array($customQuestion->type, ['checkbox', 'radio_btn', 'select_menu']))
                                {!! $customQuestion->getHtmlInput(
                                    $customQuestion->name,
                                    $customQuestion->options,
                                    ($customQuestion->pivot->required == '1'),
                                    'form-control',
                                    $customQuestion->type)
                                !!}
                            <!-- if the checkbox is of type text, textarea, file-->
                            @else
                                {!! $customQuestion->getHtmlInput(
                                    $customQuestion->name,
                                    [],
                                    ($customQuestion->pivot->required == '1'),
                                    'form-control',
                                    $customQuestion->type)
                                !!}
                            @endif
                            <input type="hidden"
                                   name="participant_question_required[]"
                                   value="{{ $customQuestion->pivot->required }}">
                            <input type="hidden"
                                   value="{{ $customQuestion->id }}"
                                   name="participant_question_id[]"/>
                        </div>
                    @endforeach
                @endif
            @endforeach
        @endif
        <input type="submit" class="btn btn-primary" value="Store Registration"/>
    </form>
</div>

$rules before "$validator = Validator::make($request->all(), $rules);"显示:

array:1 [▼
  "participant_question.0" => "required|string|max:255"
]

request->all() before "$validator = Validator::make($request->all(), $rules); "显示:

array:7 [▼
  "_token" => ""
  "participant_name" => array:1 [▼
    0 => null
  ]
  "participant_surname" => array:1 [▼
    0 => null
  ]
  "rtypes" => array:1 [▼
    0 => "1"
  ]
  "participant_question" => "j"
  "participant_question_required" => array:1 [▼
    0 => "1"
  ]
  "participant_question_id" => array:1 [▼
    0 => "1"
  ]

最佳答案

根据documentation :

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }

    // Store the blog post...
}

他们似乎没有像您一样将 Validator 作为参数传递,而是静态调用该函数,而不引用请求或任何其他参数。

其次,考虑使用 nullable允许您定义可选字段的验证标志。

关于php - 商店注册工作不正常(代码总是转到 "if ($validator->passes()) {...}"的其他部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50723153/

相关文章:

Javascript修改查询

php - 如何在 Laravel 中的关系上应用reverse()?

php - 具有多列主键的 Laravel 模型

mysql - Eloquent:通过国外模型得到平均分

javascript - 图像未在 Blade View 中加载

php - 我应该使用什么格式在 MySQL 表中存储用户的首选时区?

php - 如何修复从 HTML 中提取的纯文本的句子间距?

php - 如何在更新记录时连接列值

php - Mysql内连接where值在另一个表中

php - 从数据库中检索特定用户的内容