In my MVC, I populate forms with data from the model using an array. I am using PDO and fetch associative array this gives an array of fields that I can use to populate the view.
When the user requests a new record, the array is empty and unless I explicitly test the value of every variable before use, the script falls over with a non-existant index.
My approach previously was, for new records, to setup an empty array and pass this to the view. This is fine for simple forms, but when the view needs to use 10-15 variables this is a bit tedious.
What is the preferred method of doing this?
Should my view test every field before use, or should I create the empty array. If so, should the empty array be created in the controller or the model?
As an example, If the user wants to edit an existing record, the controller passes the ID number to the model and asks it for an array of current values for the record.
The controller passes this array to the view which then incorporates the values into a form for editing.
In contrast, when the controller receives a request for a new record, it knows there is no point in asking the model for the record because its new. It can’t just call the view because the passed array does not contain the keys required by the form.
My current approach to this is to initialise an array of empty keys but this seems tedious, time wasting and prone to error as it needs to be maintained if the model changes.
eg:
$this->view->class['Code']=NULL;
$this->view->class['Description']=NULL;
$this->view->class['Image']=NULL;
$this->view->class['Judge']=NULL;
$this->view->class['Entries']=NULL;
$this->view->class['Absentees']=NULL;
etc
There has to be a better way?
This is kind of a band-aid for poor MVC design, but you could use a function like this,
In the view if you normal did
$class['Description']you would now use
idx($class, 'Description')You should not have to pass each attribute of your model individually. Instead, just pass the entire model object and access it from the view. Example:
$this->view->entry = $myModelInstance;where$myModelInstanceis an instance ofEntryor whatever class has the Code, Description, Image, Judges, etc attributes.Then in the view, use something like
$entry->Description