Как обработать этот контекст проверки? - PullRequest
0 голосов
/ 27 апреля 2018

У меня есть эта регистрационная форма ниже.

// registration form in the registration page


 <form method="post" id="step1form" action="">
      {{csrf_field()}}
        <p>Is not necessary additional info.
       Your tickets will be sent to the email
     <b>
    {{ (\Auth::check()) ? Auth::user()->email : old('email')}}</b>.</p>

      @if (!empty($allParticipants))
        @if($allParticipants == 1)
            @foreach($selectedTypes as $selectedType)
                @foreach(range(1,$selectedType['quantity']) as $test)
                  <p>Please enter  the following 
                  information for each participant</p>
                  <div class="form-group font-size-sm">
                    <label for="name" class="text-gray">Name</label>
                    <input type="text" required class="form-control" id="name"
                           name="name" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
                  </div>
                  <div class="form-group font-size-sm">
                    <label for="surname" class="text-gray">Surname</label>
                    <input type="text" id="surname" required class="form-control" name="surname" value="{{ (\Auth::check()) ? Auth::user()->surname : old('surname')}}">
                  </div>

                <h6>Participant - 1 - {{$test}}</h6>

              <div class="form-group font-size-sm">
                <label for="participant_name" class="text-gray">Name</label>
                <input type="text" name="participant_name[]" required class="form-control" value="">
              </div>
              <div class="form-group font-size-sm">
                <label for="participant_surname" class="text-gray">Surname</label>
                <input type="text" required class="form-control" name="participant_surname[]" value="">
              </div>
            <input type="hidden" name="ttypes[]" value="{{ $selectedType['id'] }}"/>
              @foreach($selectedType['questions'] as $customQuestion)
              <div class="form-group">
                <label for="participant_question">{{$customQuestion->question}}</label>
                <input type="text"
                       @if($customQuestion->pivot->required == "1") required @endif
                class="form-control" name="participant_question[]">
                <input type="hidden" name="participant_question_required[]"
                       value="{{ $customQuestion->pivot->required }}">
                <input type="hidden" value="{{ $customQuestion->id }}" name="participant_question_id[]"/>
              </div>
              @endforeach
            @endforeach
        @endforeach
        @endif
      @endif
      <input type="submit" href="#step2" id="goToStep2" value="Go to step 2"/>
    </form> 

Если в таблице конгрессов столбец «all_participants» равен «1», пользователю необходимо ввести некоторую регистрационную информацию, чтобы ввести информацию (имя и фамилию) каждого участника.

Если столбец all_participants равен «0», он отображается как «<p>Is not necessary additional info.</p>», и пользователю не нужно вводить какую-либо информацию для регистрации в конгрессе, поскольку он использовал свою информацию для аутентификации для регистрации в конгрессе.

Но когда столбец all_participants равен "0", возникает проблема. Потому что в RegistrationController в методе, который обрабатывает регистрацию, у меня есть несколько правил:

 $rules = [
            'name' => 'required|max:255|string',
            'surname' => 'required|max:255|string',
            'email' => 'required|max:255|email',
            'participant_name.*' => 'required|max:255|string',
            'participant_surname.*' => 'required|max:255|string',
        ];

Проблема: Таким образом, когда столбец all_participants равен «0» и пользователь нажимает «перейти к шагу 2», появляются некоторые ошибки проверки. Вы знаете, как исправить проблему?

полный метод, который обрабатывает регистрацию:

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

        $user = Auth::user();

        $rules = [
            'name' => 'required|max:255|string',
            'surname' => 'required|max:255|string',
            'email' => 'required|max:255|email',
            'participant_name.*' => 'required|max:255|string',
            'participant_surname.*' => 'required|max:255|string',
            'participant_email.*' => 'required|max:255|email',
        ];

        $messages = [
            'participant_question.*.required' => 'The participant is required'
        ];

        if($request->participant_question_required){
            foreach ($request->participant_question_required as $key => $value) {
                $rule = 'string|max:255'; 
                // if this was required, ie 1, prepend "required|" to the rule
                if ($value) {
                    $rule = 'required|' . $rule;
                }

                // individual rule for this array key to the $rules array
                $rules["participant_question.{$key}"] = $rule;
            }
        }

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

        if($validator->passes())
        {
            $registration = Registration::create([
                'congress_id' => $id,
                'main_user_id' => $user->id,
                'status' => 'C',
            ]);
                if($request->participant_name) {

                    $participants = [];

                    for ($i = 0; $i < count($request->participant_name); $i++)
                        $participants[] = Participant::create([
                            'name' => $request->participant_name[$i],
                            'surname' => $request->participant_surname[$i],
                            'email' => $request->participant_email[$i],
                            'registration_id' => $registration->id,
                            'ticket_type_id' => $request->ttypes[$i]
                        ]);
                    for ($i = 0; $i < count($request->participant_question); $i++)
                        $answer = Answer::create([
                            'question_id' => $request->participant_question_id[$i],
                            'participant_id' => $participants[$i]->id,
                            'answer' => $request->participant_question[$i],
                        ]);
                }
                else{
                    $participant = Participant::create([
                        'name' => $request->name,
                        'surname' => $request->surname,
                        'email' => $request->email,
                        'registration_id' => $registration->id,
                        'ticket_type_id' => '1'
                    ]);
                }
    }

// storeRegistrationInfo () теперь выглядит так:

public function storeRegistrationInfoF(Request $request, $id, $slug = null, Validator $validator){

        $allParticipants = Congress::where('id', $id)->first()->all_participants;

        if($allParticipants){
            $user = Auth::user();

            $rules = [
                'name' => 'required_unless:all_participants,0|max:255|string',
                'surname' => 'required_unless:all_participants,0|max:255|string',
                'email' => 'required_unless:all_participants,0|max:255|email',
                'participant_name.*' => 'required_unless:all_participants,0|max:255|string',
                'participant_surname.*' => 'required_unless:all_participants,0|max:255|string',
                'participant_email.*' => 'required_unless:all_participants,0|max:255|email',
            ];

            $messages = [
                'participant_question.*.required' => 'The participant is required'
            ];


            if($request->participant_question_required){
                foreach ($request->participant_question_required as $key => $value) {
                    $rule = 'string|max:255'; 

                    // 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()) {

                $registration = Registration::create([
                    'congress_id' => $id,
                    'main_user_id' => $user->id,
                    'status' => 'C',

                ]);

                if ($request->participant_name) {

                    $participants = [];

                    for ($i = 0; $i < count($request->participant_name); $i++)
                        $participants[] = Participant::create([
                            'name' => $request->participant_name[$i],
                            'surname' => $request->participant_surname[$i],
                            'email' => $request->participant_email[$i],
                            'registration_id' => $registration->id,
                            'ticket_type_id' => $request->ttypes[$i]

                        ]);
                }
            }

            return response()->json([
                'success' => true,
                'message' => 'success'
            ], 200);
        }
        else {
            $user = Auth::user();

            $registration = Registration::create([
                'congress_id' => $id,
                'main_user_id' => $user->id,
                'status' => 'C',

            ]);
            $participant = Participant::create([
                'name' => $user->name,
                'surname' => $user->surname,
                'email' => $user->email,
                'registration_id' => $registration->id,
                'ticket_type_id' => '1' // test
            ]);
        }
        $errors = $validator->errors();
        $errors =  json_decode($errors);

        return response()->json([
            'success' => false,
            'errors' => $errors
        ], 422);
    }

1 Ответ

0 голосов
/ 28 апреля 2018

Поскольку ваша проверка всегда будет требовать, чтобы у вас были значения, независимо от того, является ли $allParticipants значение > 0 или нет, вам необходимо убедиться, что значение allParticipants больше 0, чтобы разрешить проверку, в противном случае пропустите его.

public function storeRegistration(Request $request, $id, $slug = null, Validator $validator){
  // get your `$allParticipants` here
  if($allParticipants) {
    // put your logic here
  } else{
    // get the auth user
    // and register him if there is no particpants
    $user = Auth::user();
    $registration = Registration::create([
          'congress_id' => $id,
          'main_user_id' => $user->id,
          'status' => 'C',
    ]);
  }
});

вот как должна выглядеть ваша функция:

открытая функция storeRegistrationInfoF (Запрос $ request, $ id, $ slug = null, Validator $ validator) {

    $allParticipants = Congress::where('id', $id)->first()->all_participants;

    if($allParticipants){
        $user = Auth::user();

        $rules = [
            'name' => 'required_unless:all_participants,0|max:255|string',
            'surname' => 'required_unless:all_participants,0|max:255|string',
            'email' => 'required_unless:all_participants,0|max:255|email',
            'participant_name.*' => 'required_unless:all_participants,0|max:255|string',
            'participant_surname.*' => 'required_unless:all_participants,0|max:255|string',
            'participant_email.*' => 'required_unless:all_participants,0|max:255|email',
        ];

        $messages = [
            'participant_question.*.required' => 'The participant is required'
        ];


        if($request->participant_question_required){
            foreach ($request->participant_question_required as $key => $value) {
                $rule = 'string|max:255'; 

                // 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()) {

            $registration = Registration::create([
                'congress_id' => $id,
                'main_user_id' => $user->id,
                'status' => 'C',

            ]);

            if ($request->participant_name) {

                $participants = [];

                for ($i = 0; $i < count($request->participant_name); $i++)
                    $participants[] = Participant::create([
                        'name' => $request->participant_name[$i],
                        'surname' => $request->participant_surname[$i],
                        'email' => $request->participant_email[$i],
                        'registration_id' => $registration->id,
                        'ticket_type_id' => $request->ttypes[$i]

                    ]);
            }

        return response()->json([
            'success' => true,
            'message' => 'success'
        ], 200);
      }
     if($validator->fails()) {
       $errors = $validator->errors();

       return response()->json([
        'success' => false,
        'errors' => $errors
       ], 422);
      }
    }
    else {
        $user = Auth::user();

        $registration = Registration::create([
            'congress_id' => $id,
            'main_user_id' => $user->id,
            'status' => 'C',

        ]);
        $participant = Participant::create([
            'name' => $user->name,
            'surname' => $user->surname,
            'email' => $user->email,
            'registration_id' => $registration->id,
            'ticket_type_id' => '1' // test
        ]);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...