I have a select that adds the selected value to an array of objects when you click the an add button. It adds the first fine but on selecting the second value I get this error before I click the add button.
“Trying to get property ‘title’ of non-object (View: /Users/paulfinch/code/risk/resources/views/livewire/job-create.blade.php)”
Code in view
<div class="mt-6 sm:mt-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:border-t sm:border-gray-200 sm:pt-5">
<label for="selected_task" class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2">
Select Existing Tasks
</label>
<div class="mt-1 sm:mt-0 sm:col-span-2 text-gray-800 ">
<div class="max-w-lg rounded-md shadow-sm sm:max-w-xs">
<select id="selected_task" wire:model="selected_task" class="form-select block w-full transition duration-150 ease-in-out sm:text-sm sm:leading-5">
<option value="9999">Select An Existing Task....</option>
@foreach($tasks as $task)
@if(!in_array($task, $selected_tasks))
<option value="{{$task->id}}">
<span class="capitalize">{{$task->title}}</span>
</option>
@endif
@endforeach
</select>
</div>
<div class="my-4">
<div class="flex justify-end">
<span class="ml-3 inline-flex rounded-md shadow-sm">
<button type="button" wire:click="addSelectedTask()" class="inline-flex justify-center py-2 px-4 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition duration-150 ease-in-out">
Add
</button>
</span>
</div>
</div>
</div>
</div>
<div class="mt-6 sm:mt-5">
<div class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2">
New Added Existing Tasks
</div>
@if(count($selected_tasks) < 0)
<div class="block text-xs font-medium leading-5 text-gray-600 sm:mt-px sm:pt-2">No Existing Tasks Added.</div>
@else
{{count($selected_tasks)}}
@for($i=0; $i < count($selected_tasks); $i++)
<div class="text-xs p-2 m-2 rounded shadow bg-white flex justify-between items center">
@foreach($selected_tasks as $selected)
<div>{{$selected->title}}</div>
<div>
<button type="button" class="italic p-1 bg-red-500 text-white rounded-lg" wire:click="removeNewTask({{$selected->id}})">
Remove
</button>
</div>
@endforeach
</div>
@endfor
@endif
</div>
Here is the function in the component controller
class JobCreate extends Component
{
public $job_number = "";
public $site = "";
public $client_id = null;
public $clients = [];
public $tasks = [];
public $selected_task = null;
public $selected_tasks = [];
public $new_task = "";
public $new_tasks = [];
public function addSelectedTask()
{
if ($this->selected_task != "9999")
{
$added_task = Task::find($this->selected_task);
$this->selected_tasks[] = $added_task;
}
}
}
I am using the latest version of livewire