A
A
Alexander Yerko2014-06-05 16:16:59
CodeIgniter
Alexander Yerko, 2014-06-05 16:16:59

How to handle multiple select in php?

I ran into a problem while developing a feedback form constructor. First, fields are created in the control panel and written to the database.
Then a code is generated for each field. For a multi-select select, it goes like this

$fields[$i]['html']  = '<select name="'.$fields[$i]['id'].'"';
  if ($fields[$i]['config']['multi'] == 1) $fields[$i]['html'] .= ' multiple="multiple" ';
  $fields[$i]['html'] .= ' size="'.$size.'">';
  foreach ($items as $item){
    $fields[$i]['html']  .= '<option value="'.$item.'">'.$item.'</option>';
  }
  $fields[$i]['html']  .= '</select>';

Next, the form data is collected using the jQuery serializeArray() function and sent to the codeigniter php controller using Ajax.
In the field controller I get the following:
foreach ($fields as $field){
  if ($field['type'] == 'checkbox'){
    if($this->input->post($field['id']) == 0) $post = lang("Да", 'cf_constructor');
    else $post = lang("Нет", 'cf_constructor');
  } elseif ($field['type'] == 'menu' && $field['config']['multi'] == 1){

    for ($i = 0; $i < count($this->input->post($field['id'])); $i++){
      $post_arr[$i] = $this->input->post($field['id']);
    }
    $post = implode(",", $post_arr);
  } else {
    $post = $this->input->post($field['id']);
  }
  $message .= $field['title'].': '.strip_tags(nl2br($post)).'<br/>';
}

I collect all this in a message and send it by e-mail.
The problem is that when several items are selected in the select, the controller accepts only the last of them, but it is necessary to accept all of them.
How can I do that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Yerko, 2014-06-05
@cms_admin

If you look at what is transmitted to the server, then serializeArray() transmits all checked items, but transmits them several times in a row as follows (for example, for a field with name="2"):

form_id:1
1:Александр
2:PHP
2:HTML
2:jQuery

And I need to collect all the values ​​​​of field 2 in an array.
The problem is solved in the following way the name of the select should be given as an array name="2[]".
Then in the controller it can be converted to a string like this:
$post = implode(",", $this->input->post($field['id']));

S
Sergey, 2014-06-05
Protko @Fesor

Are you sure that serializeArray() is not the problem?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question