Dynamic Object Properties in Edit Mode

When working with model objects in the Istarel Workshop application framework, you inevitably want to display some data related to (but not intrinsic to) the object. For example, in an editor, you might want to display a calculated result. Now, you can certainly have an IWDivElement as the element in an IWFormElement (or similar object), but sometimes you want to display the information like an ordinary input element that represents a property on the model object.

One approach might be to do the value assignment on the input element manually, like so:

Partial Listing: ArtistEditor.php

function artworkCountElement()
    {
        $element = new IWTextElement(5,5);
        $element->setValue($this->workflow()->object()->artworkCount());
        $element->disable();

        return $element;
    }

    function formElements()
    {
        return [
            'name' => new IWFormElement('Name', new IWTextElement(30, 50)),
            'artwork_count' => new IWFormElement('Number of Pieces', $this->artworkCountElement())
        ];
    }

That works fine, but it's a bit verbose, and it's not ideal (in my mind) to have to do the setValue() work myself since one advantage of the form handling through the workflows is that the object's properties are automatically assigned to relevant form elements.

One alternative is to take advantage of dynamic object properties in the objectDidLoad() callback to the module.

Partial Listing: ArtistEditor.php

function objectDidLoad($artist)
    {
        $artist->artwork_count = $artist->artworkCount();
    }

    function formElements()
    {
        return [
            'name' => new IWFormElement('Name', new IWTextElement(30, 50)),
            'artwork_count' => new IWFormElement('Number of Pieces', new IWTextElement(5, 5, 'disable'))
        ];
    }

Same practical impact as the first approach, but a bit cleaner code.

Developer Note

This might be a good time to mention the difference between "disable" and "readonly" as form attributes in HTML. When you disable an element, its value is not even part of the POST data when the form is submitted. When you make an element read-only, its value is still included in the POST. In both cases, the element is not editable via the user interface.

In the framework, either is fine. Even if the "property" in question does not actually exist on the object (as for the artwork_count dynamic property, the underlying object is smart enough not to try to save it when writing changes to the database record.