How can I use the edit-text / edit-* syntax in Object Tables V3 to edit a field in a parent object?

I have a join table in my application in order to handle a many to many relationship for equipment and job, e.g.:

 <model name="equipment" label="Equipment">
        <field name="name" label="Name" type="text" />
        <has-many model="equipment_job" name="equipment_jobs" />
        <display>{name}</display>
    </model>

    <model name="job" label="Job">
        <field name="name" label="Name" type="text" />
        <field name="start_date" label="Start Date" type="date" />
        <field name="end_date" label="End Date" type="date" />
        <has-many model="equipment_job" name="equipment_jobs" />
        <display>{name}</display>
    </model>

    <model name="equipment_job" label="Equipment Job">
        <belongs-to model="equipment" />
        <belongs-to model="job" />
        <display>{equipment} {job}</display>
    </model>

In my view, I want to be able to edit fields on both equipment and job, so my query is for equipment_jobs. Do the edit-* functions allow me to access parent objects of join tables so that I can, e.g. edit a job start_date or end_date without adding more UI components?

Yes, this is possible. Let's take edit-text and edit-date as examples. This will require very little effort from the xml, and a bit more in the javascript to accomplish.

Here is the example table xml for the above join table I want to edit:

<object-table label="Jobs" query="equipment_jobs" empty-message="No Jobs for this equipment yet">
        <column heading="Equipment Name" display="{equipment.name}"> 
            <edit-text value="$object.equipment.name" on-change="$:handleParentUpdate($object, newValue, oldValue, 'equipment', 'name')" />
        </column>
        <column heading="Start Date" display="{job.start_date}">
            <edit-date value="$object.job.start_date" on-change="$:handleParentUpdate($object, newValue, oldValue, 'job', 'start_date')"  />
        </column>
        <column heading="End Date" display="{job.end_date}">
            <edit-date value="$object.job.end_date" on-change="$:handleParentUpdate($object, newValue, oldValue, 'job', 'end_date')"  />
        </column>
    </object-table>

And the corresponding javascript function to interpret the on-change logic:

function handleParentUpdate(object, newValue, oldValue, parentObjType, field) {
    // pass in the parentObjType to make this function re-usable

    var objectToUpdate = object[parentObjType]();
    objectToUpdate[field] = newValue;
    objectToUpdate.save();   
}

Now you can update any parent property from your join table without creating additional UI elements.

2 Likes