Search code examples
selectstatelaravel-livewirealpine.js

laravel livewire if selected option is others add dynamic input


order.blade.php (step component)

<div class="mt-2">
    <x-input-label for="category" :value="__('Category')" />
    <x-input-select wire:model.change="state.category" :options="$categories" name="category" id="category" class="block mt-1 w-full" />
    <x-input-error :messages="$errors->get('category')" class="mt-2" />

    @if($selectedState === '6')
        <x-input-label for="others" :value="__('Specify category')" />
        <x-text-input wire:model="state.others" id="others" class="block mt-1 w-full" name="others" :value="old('others')" />
        <x-input-error :messages="$errors->get('others')" class="mt-2" />
    @endif
</div>

i.e going back and forth to steps will re render the state

Order.php

class Order extends Step
{
    public $selectedState;
    public $categories = [
        1 => 'Fabrication',
        2 => 'Housekeeping',
        3 => 'Repair',
        4 => 'Events',
        5 => 'Transport',
        6 => 'Others'
    ];

    /*
     * Initialize step fields
     */
    public function mount()
    {

        $this->mergeState([
            'category'      => $this->model->category,
            'location'      => $this->model->location,
            'destination'   => $this->model->destination,
            'date'          => $this->model->date,
            'others'          => $this->model->others,
            'quantity'          => $this->model->quantity,
            'pax'          => $this->model->pax,
            'description'          => $this->model->description,

        ]);
    }


public function updatedStateCategory($name, $value)
{
   // Something you want
   $this->selectedState = $name;
}
}

how does the state act in livewire? I've read documentation on the wizard package and haven't fully grasped

Livewire Component

<?php

namespace App\Livewire;

use App\Models\User;

use App\Steps\Order;
use App\Models\Order as Request;
use App\Steps\General;
use Livewire\Component;
use Vildanbina\LivewireWizard\WizardComponent;

class RequestForm extends WizardComponent
{
    // My custom class property
    public Request $order;

    public function model()
    {
        return new Request;
    }

    public array $steps = [
        General::class,
        Order::class,
        // Other steps...
    ];
}

UPDATED: Still haven't found out on how to incorporate this scenario. Is there a better workaround suggestion that may improve my approach?


Solution

  • selectedState must be preset before rendering the view:

    public function render()
    {
        $this->selectedState = $this->state['category'];
        return view(/* your view */);
    }
    
    

    and updatedStateCategory() can be removed now.

    You may consider also to test directly $state['category'] instead of using an additional varible:

    @if($state['category'] == 6)
       {{-- ..... --}}
    @endif