Madushan Serasinghe
Madushan Serasinghe

Reputation: 65

Validate the array inputs value to already selected or not

I want to validate the array inputs value to already selected or not. In my case, I am using Laravel Livewire and I have dynamic inputs such as I can add new options like Size, Color. But I do not want to select the same value in two inputs like the select size in two inputs. Basically, If select the same value in the second input, I want to show it already selected.

enter image description here

Below code livewire controller,

public $i = -1;
public $inputs = [];
public $options = ['Size', 'Color', 'Material', 'Style'];
public $option_name; 

function rules()
{
    $rules = [];

    if ($this->inputs) {
        foreach ($this->inputs as $key => $val) {
            $rules['option_name.' . $val] =  ['required'];
        }
        return $rules;
    }
}

public function addLine($i)
{  
    $i = $i + 1;
    $this->i = $i;
    array_push($this->inputs, $i);
}

public function updated($propertyName)
{ 
    if ($this->inputs) {
        $this->validateOnly($propertyName);
    }
} 

Below code livewire view code,

@forelse ($inputs as $key => $value)
    <x-native-select label="Option name" :options="$options" wire:model="option_name.{{ $value }}"/> // I am using livewire-wireui 
@empty
@endforelse
    
<a wire:click="addLine({{ $i }})" class="mt-4 text-sm cursor-pointer">
    + Add another option
</a>

Any idea how to validate this?

Upvotes: 0

Views: 209

Answers (1)

mrtorks
mrtorks

Reputation: 66

Try this and let me see how it goes.

public function updatedOptionName($selectedOption) {
//You can use laravel collection filter as well depending on how commplicated you want it
  $this->options = array_filter($this->options, function ($value) {
    return $value != $selectedOption;
  }, ARRAY_FILTER_USE_BOTH));
}

The above function would filter out the selected option so that the option is not available when it is already selected. It might be overkill and subject to improvement from the community. All reviews are welcome. One thing to note is that you might want a sort of reset method in case the user decides to start all over again. Something along the lines of public $originalOptions that you would want to set on mount and then a reset function that assigns this->options to it. Let me know if it works.

More info on those functions Lifecycle hooks

Upvotes: 0

Related Questions