nova-package-development
nova-package-development copied to clipboard
Create a Custom field set value based on another field and still editable
laravel 5.8 Nova 2.0.0
I have two field based on first field I want to set the value of second and it is upto the user to use the set value or may insert a new one and submit the form.
I am adding custom field like
CustomField::make('Field 2', 'field_2')->dependsOn('field_1'),
Now in CustomField class dependsOn() method I can access, the dependsOn field name, that is field_1, also in Vue > FormField.vue I can access it as {{ field.dependsOnField }} in template and as console.log(this.field.dependsOnField); in JS part, but how I can get the value of field_1 and also on change I can get new value, I am new to Vue JS, but I tried it like
export default {
mounted() {
this.registerDependencyWatchers(this.$root)
},
methods: {
registerDependencyWatchers(root) {
//console.log('working 0');
console.log(this.field.dependsOnField);
root.$children.forEach(component => {
if (this.componentIsDependency(component)) {
// console.log('working 1');
console.log(component.$attrs);
component.$watch('value', async (value) => {
console.log('working 2');
// this.dependencyValues[component.field.attribute] = value;
// this.supplier = value;
// var attr = (await Nova.request().post("/custom-field/nova-component/custom-field/supplier", {
// dependKey: component.field.attribute,
// dependValue: value
// })).data;
// this.supplier = attr.supplier;
this.registerDependencyWatchers(component)
});
}
});
},
componentIsDependency(component) {
console.log(component);
console.log(component.$attrs);
console.log(component.field);
if(component.field === undefined) {
return false;
}
for (let dependency of this.field.dependsOnField) {
console.log(dependency);
if(component.field.attribute === dependency.field) {
return true;
}
}
return false;
},
}
} `componentIsDependency` is always returning false as `component.field` is undefined and if I am returing true there `component.$watch('value', async (value) => {` is not running, I coded it by taking reference from [NovaDependencyConatiner][1] package.
You can try create the follow method in your Custom Vue Component:
findFieldByAttribute (attribute) {
return this.$parent.$children.find(brotherField =>
brotherField.field.attribute === attribute,
);
}
Usage:
const field1 = this.findFieldByAttribute('field_1');
const field1Value = field1.value;