skip to Main Content

I have a dynamic row created, and I want to remove the row but only the data from that row is removed and the input fields are not updated. I am using Livewire in this for creating the row and removing the row.
The UI of the input fields are not removed.

I have tried this but this only removed the data from the row.

This is the button code:

public function removeRow($index){
   array_splice($this->createChallanRequest['order_details'], $index, 1);
}
 

2

Answers


  1. Chosen as BEST ANSWER

    After unset the array we need to update the array again with the new data and update the index number as well.

    unset($this->request['details'][$index]); 
    $this->request['detail'] = array_values($this->request['detail'])
    

  2. I assume you are using a loop to display the rows. To let Livewire understand which rows to update in the DOM, you need to provide a unique wire:key attribute for each row:

    @foreach ($users as $user)
        <div wire:key="user-{{ $user->id }}">
            User name: {{ $user->name }}
        </div>
    @endforeach
    

    In this example I have used the record id with a prefix (useful if you have multiple lists on the same page) as wire:key

    If you are displaying an array and don’t have a unique id in the rows, you can use the array index, but you must ensure that it doesn’t get recycled (neither when you alter the rows nor when you paginate them):

    @foreach ($order_details as $key => $order_detail)
    
        <div wire:key="prefix-{{ $key }}">
            .....
            
            <button wire:click="removeRow({{ $key }})">
               DELETE
            </button>
        
        </div>
    
    @endforeach
    

    So when you delete a row you can’t use splice() for this purpose because it compacts the indexes. You can use a simply unset() that deletes the rows but leaves the indexes as they are:

    public function removeRow($index){ 
       // I assume that  $this->createChallanRequest  is a property
       unset ($this->createChallanRequest['order_details'][$index]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search