Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

php - How to use Nested Form Fields in Livewire?

I have a component called project-form and in that again I am calling another component called search-users. The problem is that I am unable to set the $members property in ProjectForm from nested component i.e search-users.

As I can understand $members must be looking to set in SearchUsers.php but I want that must be set in ProjectForm.php so I could save in db.

project-form.blade.php

<form wire:submit.prevent="submit">
   <input wire:model="name"/>
   <input wire:model="category"/>
   <input wire:model="target_date"/>

   @livewire('search-users')
</form>

ProjectForm.php

<?php

namespace AppHttpLivewire;

use AppModelsProject;
use LivewireComponent;

class ProjectForm extends Component
{

    public string $name = '';
    public string $category = '';
    public string $target_date = '';
    public array $members = [];
    
    protected $rules = [
        'name' => 'required',
        'category' => 'required',
        'target_date' => 'required',
    ];

    public function submit(){
        
        $validated = $this->validate();
        Project::create($validated);
        toastr()->success('Project Created Successfully');
    }

    public function render()
    {
        return view('livewire.project-form');
    }
}

search-users.blade.php

@foreach($users as $user)
    <label class="list-group-item ps-0 border-0 d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
            <img alt="{{ $user->name }}" src="{{ url('storage/'.$user->avatar) }}" width="35" class="me-3 rounded-circle mx-auto d-block">
            {{ $user->name }}
        </div>
        <input class="form-check-input me-1" wire:model.defer="members" type="checkbox" value="{{ $user->id }}">
    </label>
@endforeach
question from:https://stackoverflow.com/questions/65867988/how-to-use-nested-form-fields-in-livewire

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As already suggestes by @Qirel you should use Livewire events.

In your search components you could emit an event memebersFound and passing the members from your search as parameter (see Livewire Passing parameters in events) like this

$this->emit('membersFound', $membersFound);

Then, in your ProjectForm component you should listen for this event

protected $listeners = [
  'membersFound' => 'addMembers'
];

public function addMembers(array $members)
{
  $this->members = $members;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...