Reputation: 635
How do I send an array from the model- to the view-file?
Background: I have a form where name can be put into (View-file). Then I pass this info on to my controller-file, which check if there is information added to the form. If not error message shows up and tells the user that names must be added. If names has been added to the form the controller then pass the info over to the model which check the database if any of the names already exists in the database. If some or all names already exists in the database they are passed on to an array. If the name is NOT added to the database the model-file adds them to the database.
I want to get the array of the names which already are in the database and output these for the user. So this is why I need the array with the names already in the database.
User add:
Mark
Sophie
Dan
Josh
Already in database:
Mark
Dan
Array then contains (should be output to the user):
Mark
Dan
One solution I thought was possible was to add a return statement to the function in the model-file. And retrive the array like this:
$data['nameArray'] = $this->model_name->add_name();
But this won't work, because if the user have missed to add information to the form the else statement will be shown and the $data['nameArray'] will not be defined. Which lead to the error message "Undefined variable", when trying to output it in the view-file.
Upvotes: 0
Views: 1346
Reputation: 4284
There is no difficulty passing arrays from a model to a controller or view in codeigniter. Pass them like you would any other variable.
You idea seems like it should work. If you want to prevent the "undefined variable" error you can use isset()
in your view like so:
<?php if isset($nameArray) echo $nameArray; ?>
Which would only echo a name array if it had been returned by your model.
Alternatively you could do as atno said and add a check in the controller itself:
$data['nameArray'] = $this->model_name->add_name();
if ( ! $data['nameArray']) $data['nameArray'] = array();
There are other methods to do this as well, whichever is best depends on your situation and preferences.
Upvotes: 2
Reputation: 4984
before adding the model result to the array check if the result is empty, if empty add a value like $data['nameArray'] = "N/A"
else if it isn't empty $data['nameArray'] = $this->model_name->add_name();
then in your view check if $nameArray is array and proceed using that array else display the string N/A. That's how im doing it
if the user have missed to add information to the form if your users must enter this value you must force them to do, check the Form_Validation library for codeigniter.
Upvotes: 1