<template> <div class="field"> <label for="attribute-value"> {{ attribute.label }} </label> <div> <FeatureExtraForm :id="`attribute-value-for-${attribute.name}`" ref="extraForm" name="attribute-value" :field="{ ...attribute, value }" :use-value-only="true" @update:value="updateValue($event.toString(), attribute.id)" /> </div> </div> </template> <script> import FeatureExtraForm from '@/components/Feature/Edit/FeatureExtraForm'; export default { name: 'ProjectAttributeForm', components: { FeatureExtraForm, }, props: { attribute: { type: Object, default: () => { return {}; } }, formProjectAttributes: { type: Array, default: () => { return []; } } }, computed: { /** * Retrieves the value of a project attribute from project data. * * @returns {String|null} The current value of the attribute for the project if set; */ value() { // Find the attribute within the project's current attributes array. const projectAttribute = this.formProjectAttributes.find(el => el.attribute_id === this.attribute.id); // If the attribute is set in this project, return its value, otherwise return the attribute's default value. return projectAttribute ? projectAttribute.value : this.attribute.default_value; }, }, methods: { /** * Updates the value of a project attribute or adds a new attribute if it does not exist. * * This function looks for an attribute by its ID. If the attribute exists, its value is updated. * If the attribute does not exist, a new attribute object is added to the `project_attributes` array. * * @param {String} value - The new value to be assigned to the project attribute. * @param {Number} attributeId - The ID of the attribute to be updated or added. */ updateValue(value, attributeId) { let projectAttributes = [...this.formProjectAttributes]; // Find the index of the attribute in the project_attributes array. const attributeIndex = projectAttributes.findIndex(el => el.attribute_id === attributeId); if (attributeIndex !== -1) { // Directly update the attribute's value if it exists. projectAttributes[attributeIndex].value = value; } else { // Add a new attribute object if it does not exist. projectAttributes.push({ attribute_id: attributeId, value }); } this.$emit('update:project_attributes', projectAttributes); } } }; </script>