@rodrigo.pedra Thank you. I tried your solution but it doesn't work.
I tried a few things:
The component:
protected $rules = ['qty'=>'array', 'qty.*'=>'numeric'];
protected $messages = ['qty.*.numeric'=>'Please enter the quantity'];
My input field:
<input type="text" class="form-control @error('qty.{{$model->id}}') is-invalid @enderror"
wire:model.lazy="qty.{{$model->id}}">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon-quantity" wire:click.prevent="addSpare({{$model->id}})">Add</button>
</div>
<x-display_error error="qty{{$model->id}}"/>
</div>
No errors displayed now.
I tried:
<input type="text" class="form-control @error('qty') is-invalid @enderror"
wire:model.lazy="qty.{{$model->id}}">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon-quantity" wire:click.prevent="addSpare({{$model->id}})">Add</button>
</div>
<x-display_error error="qty"/>
</div>
All inputs get the error: The qty must be an array.
I also tried a few other things:
public function addSpare($spareId)
{
if(empty($this->qty))
$this->addError('qty.'.$spareId, 'Qty empty');
return Redirect::route('jobs.edit', ['job'=>$this->job, 'selectedTab'=>'#tab2']);
Didn't get the errors and it tried to do this:
$this->job->spares()->attach($spareId, ['qty' => $this->qty[$spareId]]);
which of course gave the error: Undefined offset: 13
I tried:
public function addSpare($spareId)
{
$errors = $this->getErrorBag();
if(empty($this->qty))
$errors->add('qty.'.$spareId, 'Some message');
$this->job->spares()->attach($spareId, ['qty' => $this->qty[$spareId]]);
return Redirect::route('jobs.edit', ['job'=>$this->job, 'selectedTab'=>'#tab2']);
}
Again, tried to do the attach part and gave me this error:
Trying to access array offset on value of type null
I tried:
public function addSpare($spareId)
{
$this->withValidator(function (Validator $validator) use($spareId) {
$validator->after(function ($validator) use($spareId){
if (empty($this->qty)) {
$validator->errors()->add('qty.'.$spareId, 'Something is wrong with this field!');
}
});
})->validate();
$this->job->spares()->attach($spareId, ['qty' => $this->qty[$spareId]]);
return Redirect::route('jobs.edit', ['job'=>$this->job, 'selectedTab'=>'#tab2']);
}
Didn't get any errors.
I ended up doing this:
public function addSpare($spareId)
{
if(empty($this->qty[$spareId)) {
alert()->error('Error!', 'Please enter the quantity');
} elseif(!is_numeric($this->qty[$spareId])) {
alert()->error('Error!', 'The quanity must be a number');
} else {
$this->job->spares()->attach($spareId, ['qty' => $this->qty[$spareId]]);
}
return Redirect::route('jobs.edit', ['job'=>$this->job, 'selectedTab'=>'#tab2']);
}
Lost the will to live LOL
Thanks for trying to help.