Reputation: 317
I have a text input which is populated by values from the database passed from the controller. This is how I have done it:
<input type="text" class="form-control" id="groupname" name="groupname" disabled value="<?php foreach ($result as $r) {
echo $r->group_name;
};?>"/> <br>`
This code should be executed once a search button is clicked and its working well. My problem is, every time I load the view,this input field is loaded meaning this code executed and since I have not searched anything, it is giving me an error. How can I set the default value of the input box to be null/empty by default or if no value is returned from the controller.
Am a newbie. Your help is much appreciated.
Upvotes: 0
Views: 988
Reputation: 2071
You can check whether search performed or not by checking your array
<input type="text" class="form-control" id="groupname" name="groupname" disabled value="<?php if(isset($result) && !empty($result)){ foreach ($result as $r) {
echo $r->group_name;
} };?>"/> <br>`
Explanation
I use if(isset($result) && !empty($result)){
condition in this i have checked that if your search happens that means there $result
will be set and there must be something in $result
.
But if you simply refresh page then there is no value in $result
so it will not process foreach
loop.
Upvotes: 1
Reputation: 775
You should set empty array with $result = array();
before your call to the function, or you can do it in the foreach()
, like this foreach((array)$result as $r)
... see more here: foreach()
Upvotes: 1
Reputation: 1461
you could try this:
<input type="text" class="form-control" id="groupname" name="groupname" disabled value="
<?php
if(count($result)>0){
foreach ($result as $r) {
echo $r->group_name;
}
}?>"/> <br>
Upvotes: 1