Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9693

How to access value of nova field in another custom field vue component

PHP 7.3

Laravel 5.8

I am creating a form field total, that is the multiplication of value from two other fields quantity and price

This is my code

export default {
    mixins: [FormField, HandlesValidationErrors],

    props: ['resourceName', 'resourceId', 'field'],

    computed: {
        calculatedTotal: function () {
            //return parseFloat(field.price) * parseFloat(field.quantity);
            return 10;
        }
    },

    methods: {
        /*
         * Set the initial, internal value for the field.
         */
        setInitialValue() {
            this.value = this.field.value || ''
        },

        /**
         * Fill the given FormData object with the field's internal value.
         */
        fill(formData) {
            formData.append(this.field.attribute, this.value || '')
        },

        /**
         * Update the field's internal value.
         */
        handleChange(value) {
            this.value = value
        },
    },
}

and template

<template slot="field">
   <input
         :id="field.name"
         type="text"
         class="w-full form-control form-input form-input-bordered"
         :class="errorClasses"
         :placeholder="field.name"
         v-model="calculatedTotal"
      />
 </template>

I am unable to access those values here, the quantity field is Laravel Nova default Number field and the price field is Money field. with the commented code above I am getting error, undefined field.

Upvotes: 1

Views: 3423

Answers (1)

bordieris
bordieris

Reputation: 11

If you're inside a field, I think you should look for other fields inside current field's parent. In similar cases I did something like:

calculatedTotal: function () {
    return parseFloat(this.getElementValue(this.$parent, 'price')) * parseFloat(this.getElementValue(this.$parent, 'quantity'));
}

and in methods section I created the getElementValue as a method looking into all children of the passed parent and getting value for the one with the passed attribute:

        getElementValue(root, elemName){
            let value = null
            root.$children.forEach(component => {
                if (component.field !== undefined && component.field.attribute == elemName) {
                    value = component.field.value
                }
            })
            return value
        }

Upvotes: 1

Related Questions