Welcome Guest, Not a member yet? Register   Sign In
Dynamic dropdown doesn't work
#1

[eluser]soluicius[/eluser]
Hi guys.
I have a problem with dynamic dropdown. I get this error:
Code:
A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: helpers/form_helper.php

Line Number: 331

my view:
Code:
<tr>
  <td>Parent</td>
  <td>&lt;?php echo form_dropdown('parent_id', $pages_no_parents, $this->input->post('parent_id') ? $this->input->post('parent_id') : $page->parent_id); ?&gt;</td>
</tr>

here is my model:
Code:
class Page_m extends MY_Model {
protected $_table_name = 'pages';
protected $_order_by = 'order';
public $rules = array(
   'parent_id' => array(
     'field' => 'parent_id',
     'label' => 'Parent',
     'rules' => 'trim|intval'
   ),
   'title' => array(
     'field' => 'title',
     'label' => 'Title',
     'rules' => 'trim|required|max_length[100]|xss_clean'
   ),
   'slug' => array(
     'field' => 'slug',
     'label' => 'Slug',
     'rules' => 'trim|required|max_length[100]|url_title|callback__unique_slug|xss_clean'
   ),
   'body' => array(
     'field' => 'body',
     'label' => 'Body',
     'rules' => 'trim|required'
   ),
);

public function get_new() {
  $page = new stdClass();
  $page->title = '';
  $page->slug = '';
  $page->body = '';
  $page->parent_id = 0;
  return $page;
}

public function get_no_parents() {
  //Fetch pages without parents
  $this->db->select('id, title');
  $this->db->where('parent_id', 0);
  $pages = parent::get();
  
  //Return key => value pair array
  $array = array(0 => 'No parent');
  if (count($pages)){
    foreach($pages as $page){
     $array[$page->id] = $page->title;
    }
    
  
  }
}
}

and finally controller:
Code:
//Pages for dropdown
   $this->data['pages_no_parents'] = $this->page_m->get_no_parents();
   dump($this->data['pages_no_parents']);


#2

[eluser]jonez[/eluser]
If you're getting that error $pages_no_parents is not an array. die(var_dump($pages_no_parents)); right before you call the view and look at the data.
#3

[eluser]CroNiX[/eluser]
I don't see anything being returned from your get_no_parents() method. You need to
Code:
return $array;
#4

[eluser]CroNiX[/eluser]
Also, if you use the form_helper, you can rewrite this
Code:
<td>&lt;?php echo form_dropdown('parent_id', $pages_no_parents, $this->input->post('parent_id') ? $this->input->post('parent_id') : $page->parent_id); ?&gt;</td>
so you don't have to to that ternary operator there as
Code:
<td>&lt;?php echo form_dropdown('parent_id', $pages_no_parents, set_value('parent_id', $page->parent_id)); ?&gt;</td>
Code:
set_value(field_name, default_value_if_not_posted);
http://ellislab.com/codeigniter/user-gui...elper.html
#5

[eluser]soluicius[/eluser]
Thank you CroNiX,
Code:
return $array
fixed itSmile




Theme © iAndrew 2016 - Forum software by © MyBB