Как правильно хранить необходимую информацию для регистрации пользователя и других участников конгресса?(сценарий 1 работает, но сценарий 2 и 3 - нет) - PullRequest
0 голосов
/ 25 апреля 2018

У меня есть форма регистрации ниже для регистрации пользователя на конгрессе.Есть 4 разных сценария для регистрации.Таким образом, регистрационная форма должна обрабатывать 4 различных сценария.Но это не работает, только сценарий 1 работает нормально.

Знаете ли вы, как достичь этого сценария?

Сценарий 1: (единственный сценарий, который работает нормально)

  • есть два типа заявок на конгресс: «тип заявки 1» и «заявка типа 2»
  • тип заявки «tt1» имеет пользовательский вопросник «Что этоphone? ", билет типа" tt2 "не имеет какого-либо пользовательского вопроса, связанного
  • все участники -" 1 ", что означает, что необходимо собрать информацию (имя и фамилию) каждого участника
  • Схема для этого сценария: enter image description here

Сценарий 2:

  • Есть два типа билетов на конгресс "tt1 "и" tt2 "
  • с типами заявок" tt1 "и" tt2 "не связан пользовательский вопрос
  • всем участникам соответствует" 1 ", что означает, что необходимо собирать информацию о каждомучастник
  • Диаграмма для этого сценария:

enter image description here

Сценарий 3:

  • Существует два типа билетов на конгресс: "tt1" и "tt2"
  • тип заявкиУ «tt1» есть пользовательский вопросник «Whats your phone?», с типом заявки «tt2» не связан пользовательский вопрос
  • у всех участников «0», что означает, что нет необходимости собирать информацию (имяи фамилия) каждого участника
  • Диаграмма для этого сценария: enter image description here

Сценарий 4:

  • есть два типа заявок на конгресс "tt1" и "tt2"
  • с типами заявок "tt1" и "tt2" не связано ни одного пользовательского вопроса
  • все участники is "0 ", что означает, что нет необходимости собирать информацию (имя и фамилию) каждого участника
  • Диаграмма для этого сценария: enter image description here

Выбранныйбилеты с предыдущей страницы доступны в переменной «$selectedTypes»

// регистрационная форма при регистрации.blade.php page

      <form method="post" id="step1form" action="">
    {{csrf_field()}}
    @if (!empty($allParticipants))
        @if($allParticipants == 1)
            <p>Please fill in all fields. Your tickets will be sent to
                p{{ (\Auth::check()) ? Auth::user()->email : old('email')}}.</p>

            @foreach($selectedTypes as $k => $selectedType)
                @foreach(range(1,$selectedType['quantity']) as $val)

                    <h6>Participant - {{$val}}  - {{$k}}</h6>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="payment_method" value="referencias">
                        <label class="form-check-label d-flex align-items-center" for="exampleRadios1">
                            <span class="mr-auto">Fill the following fields with the authenticated user information.</span>
                        </label>
                    </div>
                    <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
            @else
                <p>Its not necessary aditional info. Your tickets will be sent to {{ (\Auth::check()) ? Auth::user()->email : old('email')}}.</p>

            @endif
        @endif

    <input type="submit" href="#step2"
           id="goToStep2Free" class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>

// registration.blade.php завершенный метод регистрации пользователя в конгрессе

public function StoreUserInfo(Request $request, $id, $slug = null, Validator $validator){
    $allParticipants = Congress::where('id', $id)->first()->all_participants;
    $user = Auth::user();

    if($allParticipants){
        $rules = [
            'participant_name.*' => 'required|max:255|string',
            'participant_surname.*' => 'required|max:255|string',
        ];

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

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

            // add the 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_participant_id' => $user->id,
                'status' => 'C',
            ]);

            $participants = [];

            for ($i = 0; $i < count($request->participant_name); $i++)
                $participants[] = Participant::create([
                    'name' => $request->participant_name[$i],
                    'surname' => $request->participant_surname[$i],
                    'registration_id' => $registration->id,
                    'ticket_type_id' => $request->rtypes[$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],
                ]);
            }

        return response()->json([
            'success' => true,
            'message' => 'success'
        ], 200);
    }


    else {

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


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

            // add the 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_participant_id' => $user->id,
                'status' => 'C',

            ]);

            $participants = [];

            for ($i = 0; $i < count($request->participant_name); $i++)
                $participants[] = Participant::create([
                    'name' => '',
                    'surname' => '',
                    'registration_id' => $registration->id,
                    'ticket_type_id' => $request->rtypes[$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],
                ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'success'
        ], 200);

    }
}

Соответствующие модели на вопрос:

class Congress extends Model
{
    // A conference has many ticket types
    public function ticketTypes(){
        return $this->hasMany('App\TicketType', 'congress_id');
    }

    public function registrations(){
        return $this->hasMany('App\Registration', 'congress_id');
    }
}

// RegistrationModel
class Registration extends Model
{
    // a registration has one user that do the registration (main_participant_id)
    public function customer(){
        return $this->belongsTo('App\User');
    }
    public function congress(){
        return $this->belongsTo('App\Congress');
    }
}

class TicketType extends Model
{
    public function congress(){
        return $this->belongsTo('App\Congress');
    }
}

class Question extends Model
{
    public function registration_type(){
        return $this->belongsToMany('App\RegistrationType', 'ticket_type_questions')
            ->withPivot('required');
    }
}

class Answer extends Model
{
    public function question(){
        return $this->belongsTo('Question');
    }
    public function participant(){
        return $this->belongsTo('Participant');
    }
}

Диаграмма, которая показывает некоторые проблемы с кодом, который у меня есть на данный момент, который является кодом в вопросе:

enter image description here

Ответы [ 3 ]

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

Если вы хотите сохранить более одного типа ticket_type для участника, вам необходимо использовать сводную таблицу.Сводная таблица - это таблица, которая содержит только идентификаторы и связывает данные вместе многими-многими-способами.

например,

participants_ticket_type table
id      ticket_type_id   participant_id
1          1               2
2          2               2

Обратите внимание, как участник 2 имеет ticket_types 1 и 2?Это отношения многие ко многим.

Laravel обрабатывает эти отношения для вас, и вы можете найти их в их документах.https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

Обычно, если вы обнаружите, что храните более 1 идентификатора в столбце, отношение многие ко многим решит эту проблему.

0 голосов
/ 04 мая 2018

Я вижу две вещи

1.- Форма ничего не отправляет, когда $ allParticipants == 0, может быть что-то более похожее на:

    <form method="post" id="step1form" action="">
    {{csrf_field()}}
    @if (!is_null($allParticipants) && is_int($allParticipants))
        @if($allParticipants == 1)   
            <p>Please fill in all fields. Your tickets will be sent to
                p{{ (\Auth::check()) ? Auth::user()->email : old('email')}}.</p>
        @else
            <p>Its not necessary aditional info. Your tickets will be sent to {{ (\Auth::check()) ? Auth::user()->email : old('email')}}.</p>
        @endif

        @foreach($selectedTypes as $selectedType)
            @foreach(range(1,$selectedType['quantity']) as $test)
                <h6>Participant - 1 - {{$test}}</h6>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="payment_method" value="referencias">
                    <label class="form-check-label d-flex align-items-center" for="exampleRadios1">
                        <span class="mr-auto">Fill the following fields with the authenticated user information.</span>
                    </label>
                </div>
                @if($allParticipants == 1)
                    <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>
                   @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
                @else
                    <input type="hidden" value="foo" name="participant_name[]"/>
                    <input type="hidden" value="bar" name="participant_surname[]"/>
                @endif
                <input type="hidden" name="ttypes[]" value="{{ $selectedType['id'] }}"/>                
            @endforeach
            @if ($allParticipants == 0) 
              @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
            @endif
        @endforeach
    @endif

    <input type="submit" href="#step2"
            id="goToStep2Free" class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
    </form>

2.- Вопросы, похоже,в зависимости от типа билета и являются дополнительными, функция должна учитывать это.

public function StoreUserInfo(Request $request, $id, $slug = null, Validator $validator){
    $allParticipants = Congress::where('id', $id)->first()->all_participants;
    $user = Auth::user();

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

    if(isset($request->participant_question_required)) {
        $messages = [
            'participant_question.*.required' => 'The participant is required'
        ];

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

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

    if($allParticipants){
        $rules = [
            'participant_name.*' => 'required|max:255|string',
            'participant_surname.*' => 'required|max:255|string',
        ];
    }

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

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

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

            ]);
        }

        if (isset($request->participant_question))
            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],
                    ]);
    }

    return response()->json([
        'success' => true,
        'message' => 'success'
    ], 200);
}

Надеюсь, что это работает!Привет

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

Прежде всего, используйте select * from TABLENAME, а затем используйте функцию COUNT в запросе. Или используйте функцию PHP Count в файле бланка laravel, затем выполните ваш код ..

в файле блэйда

@if(count($records)>0){
   // Your Code

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...