laravel - 无法使用带有 livewire 的关联键从数组中删除输入字段
问题描述
我有一个不容易解释的活线问题,但我会尽力而为。基本上,我正在使用来自序列化记录的键值对数组做一个动态表单。用户应该能够添加和删除新字段。问题在于 remove 方法,因为它似乎不接受密钥作为参数。我有什么办法可以处理这个?这是 livewire 组件:
class SetPositions extends Component
{
protected $listeners = ['updatePositions' => 'render'];
public $positions = [];
public $key;
public $value;
public function mount(){
$this->positions = Settings::where('name', '=', 'PEOPLE_POSITIONS')->pluck('value')->first();
}
public function addPosition() {
$this->positions[$this->key] = $this->value;
$this->emit('updatePositions');
}
public function removePosition($param){
dd($param);
}
<form method="post" wire:submit.prevent="update">
@csrf
@method('PUT')
@foreach($this->positions as $key => $value)
<div x-data="{ block: false}" class="sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:border-t sm:border-gray-200 sm:pt-5">
<div x-show="!block" class="block text-sm font-medium text-gray-700 sm:mt-px sm:pt-2">
<!--<input :disabled="!block" value="" type="text" class="block w-full max-w-lg border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm">-->
<label for="test" class="block w-full max-w-lg border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm">
{{$key}}
</label>
</div>
<div x-show="!block" class="mt-1 sm:mt-0 sm:col-span-1">
<input wire:model="positions.{{$key}}" type="text" class="block w-full max-w-lg border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm">
</div>
<button wire:click="removePosition({{$positions[$key]}})" @click="block = !block" type="button">
<svg class="w-6 h-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
@endforeach
解决方案
查看 Laravel 文档中的 pluck 方法。现在您可以将位置属性作为具有键值对的数组处理 https://laravel.com/docs/8.x/collections#method-pluck
推荐阅读
- jquery - 如何在 ASP.NET MVC 5 项目中使用 jquery-validation-unobtrusive 验证文件的大小?
- c# - 如何使用 AuthenticationMiddleware 和注入应用程序设置
- ios - 在自定义迁移策略中传递给模型迁移函数时,Core Data 实体中的 Int16 支持的枚举属性似乎具有不正确的值
- ethereum - 以太坊 Geth - 待处理交易
- android - 自定义 TextInputLayout 和 TextInputEditText
- python - Numpy 滚动 Columwise 相关性
- sql - SQL选择小于特定日期的最大日期
- python - sklearn.Normalization 是否有可用的 invert_transform 方法
- html - 用于更改图像的媒体查询
- hibernate - 不获取在休眠中插入的最近记录