['required', 'min:1'], 'contacts.*.firstName' => ['required', 'string', 'max:50'], 'contacts.*.secondName' => ['required', 'string', 'max:50'], 'contacts.*.phones.*' => 'required|string|regex:/^(\+7)([(]{1})([0-9]{3})([)]{1})([\s]{1})([0-9]{3})([-]{1})([0-9]{2})([-]{1})([0-9]{2})/', 'complexId' => ['required'], 'agentId' => ['required'], ]; } protected function messages() { return [ 'contacts.*.firstName.reqired' => 'Необходимо указать имя (отчество) клиента', 'contacts.*.secondName.reqired' => 'Необходимо указать фамилию клиента', 'contacts.*.firstName.max' => 'Указанное имя клиента слишком длинное', 'contacts.*.secondName.max' => 'Указанное имя клиента слишком длинное', 'contacts.*.phones.*.reqired' => 'Необходимо указать номер телефона клиента', 'contacts.*.phones.*.regex' => 'Указанный номер телефона некорректный', ]; } public function mount() { $this->status = FormStatus::NEW; $this->complexes = GetAvailableComplexes(); $this->availableAgents = GetAvailableAgents(); $this->maxContactsCount = 2; $this->maxContactPhonesCount = 1; $this->contactLabels = ['Основной контакт', 'Супруг/супруга']; if (count($this->availableAgents) == 1) //чтобы не выводить в форму { //и не заставлять пользователя указывать вручную $this->agentId = $this->availableAgents[0]['id']; } $this->contacts = []; $this->addContact(); $this->addContact();//по-умолчанию сразу выводить супруга $this->setCurrentContactIndex(0); } /** * Метод срабатывает, когда пользователь нажимает в форме * на кнопку "Добавить супруга" * @return void */ public function addContact() { if (!isset($this->contacts)) { $this->contacts = []; } if ($this->maxContactsCount > count($this->contacts)) { $this->contacts[] = [ 'firstName' => '', 'secondName' => '', 'phones' => [''] ]; } $this->setCurrentContactIndex(count($this->contacts) - 1); } /** * Метод срабатывает, когда пользователь нажимает кнопку "Удалить контакт" * Кнопка доступна на всех вкладках, кроме первой * @param mixed $index Индекс контакта по порядку следования на вкладках * @return void */ public function deleteContact($index = false) { if ($index === false) { $index = $this->currentContactIndex; } if ($index > 0) { unset($this->contacts[$index]); $this->contacts = array_values($this->contacts); $this->setCurrentContactIndex($index - 1); } } /** * Вызвается при переходе пользователя по вкладкам * @param mixed $index * @return void */ public function setCurrentContactIndex($index) { $this->currentContactIndex = $index; $this->updated('currentContactIndex'); } /** * Вызывается, когда пользователь нажимает на кнопку * "Добавить супруга" на первой вкладке * @return void */ public function toggleSecondContact() { if ($this->currentContactIndex == 0) { if (count($this->contacts) == 2) { $this->deleteContact(1); } elseif (count($this->contacts) == 1) { $this->addContact(); } } } /** * Вызывается, когда пользователь нажимает на кнопку "добавить телефон" * на вкладке любого из контактов * @return void */ public function addPhoneForCurrentContact() { if (count($this->contacts[$this->currentContactIndex]['phones']) < $this->maxContactPhonesCount) { $this->contacts[$this->currentContactIndex]['phones'][] = ''; } } public function updated($propertyName) { $this->status = FormStatus::IN_PROCESS; $this->validateOnly($propertyName); try { $this->validate(); $this->status = FormStatus::READY; } catch (\Exception $e) { $this->status = FormStatus::IN_PROCESS; } } public function render() { return view( 'clientcreateform::livewire.form' ); } public function rendered() { $this->dispatch('phoneInputAdded'); } public function resetData() { $this->mount(); } public function back() { $this->status = FormStatus::IN_PROCESS; } public function save() { if ( !$deal = Deal::create([ 'agent_id' => $this->agentId, 'complex_id' => $this->complexId ]) ) { $this->status = FormStatus::ERROR; return; } foreach ($this->contacts as $contact) { if ( !$newUser = Client::updateOrCreate( ['phone' => $contact['phones'][0]], [ 'name' => trim($contact['firstName'] . ' ' . $contact['secondName']), 'phone' => $contact['phones'][0] ] ) ) { $this->status = FormStatus::ERROR; return; } if ( !$dealClient = DealClients::firstOrCreate([ 'deal_id' => $deal->id, 'client_id' => $newUser->id ]) ) { $this->status = FormStatus::ERROR; return; } } $this->status = FormStatus::SUCCESS; $this->dispatch('clientCreated'); } }