我有一个称为Distributor
的资源
ID::make()->sortable(),
Text::make('Name')
->creationRules('required'),
BelongsTo::make('Region')
->creationRules('required')
->searchable(),
BelongsTo::make('Country')
->creationRules('required')
->searchable(),
到目前为止,一切都准备就绪。但是Country
模型应取决于Region
模型,因此当我选择一个区域时,我想显示与该区域相关的国家/地区的选项。
地区和国家/地区已经基于belongsToMany
关系在他们的模型中相关联。
是否有办法使这些字段协同工作?
我意识到这个问题已经快一年了,但是我想我会回答:1.这个问题仍然在增加流量; 2.我们最近遇到了一个相同的问题,对缺乏可用信息感到失望。
不幸的是,从Laravel Nova v2.9.3开始,如果没有创建自定义字段并自行处理逻辑,这是不可能的。 The official documentation for custom fields相当稀疏,但应该足以开始使用。
我们的自定义字段在Vue方面仍然非常简单。 Vue处理的唯一真实逻辑是从我们的API中提取国家/州,并将其填充到下拉列表中。在PHP方面,我们最终需要重写字段控制器中的两个函数:fillAttributeFromRequest()和resolve()。见下文:
CountryState.php:
namespace Gamefor\CountryState;
use Laravel\Nova\Fields\Field;
class CountryState extends Field
{
public $component = 'country-state';
/**
* Hydrate the given attribute on the model based on the incoming request.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param string $requestAttribute
* @param object $model
* @param string $attribute
* @return void
*/
protected function fillAttributeFromRequest($request, $requestAttribute, $model, $attribute)
{
parent::fillAttributeFromRequest($request, $requestAttribute, $model, $attribute);
if ($request->exists('state_id')) {
$model->state_id = $request['state_id'];
}
if ($request->exists('country_id')) {
$model->country_id = $request['country_id'];
}
}
/**
* Resolve the field's value for display.
*
* @param mixed $resource
* @param string|null $attribute
* @return void
*/
public function resolve($resource, $attribute = null)
{
// Model has both country_id and state_id foreign keys
// In the model, we have
//
// public function country(){
// return $this->belongsTo('App\Country', 'country_id', 'id');
// }
//
// public function state(){
// return $this->belongsTo('App\State', 'state_id', 'id');
// }
$this->value = $resource->country['name'] . ', ' . $resource->state['name'];
}
}
FormField.vue
<template>
<default-field :field="field" :errors="errors">
<template slot="field">
<select
name="country"
ref="menu"
id="country"
class="form-control form-select mb-3 w-full"
v-model="selectedCountryId"
@change="updateStateDropdown"
>
<option
:key="country.id"
:value="country.id"
v-for="country in countries"
>
{{ country.name }}
</option>
</select>
<select
v-if="states.length > 0"
name="state"
ref="menu"
id="state"
class="form-control form-select mb-3 w-full"
v-model="selectedStateId"
>
<option :value="state.id" :key="state" v-for="state in states">
{{ state.name }}
</option>
</select>
</template>
</default-field>
</template>
<script>
import { FormField, HandlesValidationErrors } from "laravel-nova";
export default {
mixins: [FormField, HandlesValidationErrors],
props: {
name: String
},
data() {
return {
countries: [],
states: [],
allStates: [],
selectedCountryId: null,
selectedStateId: null
};
},
created: function() {
this.fetchCountriesWithStates();
},
methods: {
updateStateDropdown() {
this.states = this.allStates.filter(
item => item.country_id === this.selectedCountryId
);
this.selectedStateId = this.states.length > 0 ? this.states[0].id : null;
},
async fetchCountriesWithStates() {
const countryResponse = await Nova.request().get("/api/v1/countries");
const stateResponse = await Nova.request().get("/api/v1/states");
this.countries = countryResponse.data;
this.allStates = stateResponse.data;
this.updateStateDropdown();
},
fill(formData){
formData.append('country_id', this.selectedCountryId);
formData.append('state_id', this.selectedStateId);
},
},
};
</script>
IndexField.vue
<template>
<span>{{ field.value }}</span>
</template>
<script>
export default {
props: ['resourceName', 'field',],
}
</script>
最后,在我们的Nova资源的字段数组中:
CountryState::make('Country and State')->rules('required')
希望这可以帮助任何敢于冒险进入Nova定制野兔洞的人。