Save selected values from a checkbox into a field I've the next form.

  $query = "SELECT name, tid FROM taxonomy_term_data WHERE vid=2 AND language = '$language_url';";
  $result = db_query($query);
  foreach ($result as $row2) {
     $options2[$row2-&gt;tid] = t($row2-&gt;name);
  }
  $form['group_config']['municipios'] = array(
     '#type' =&gt; 'checkboxes',
     '#title' =&gt; t('Municipios'),
     '#options' =&gt; $options2,
     '#required' =&gt; TRUE,
  );


I do a query to take the differents taxonomy terms that I have.

I don't know how to obtain the values that the user has selected and save into a field.

I've done the next code but It dosn't work.

   function anuncio_datos_usuario(&amp;$form_state,$values){
        $node = new stdClass();
        $node-&gt;title = $values['titulo'];
    $node-&gt;type = $type;
    node_object_prepare($node);
    $node-&gt;language = $values['idioma'];
    $node-&gt;uid = $userid;
    $node-&gt;status = 0; //(1 or 0): published or not
    $node-&gt;promote = 0; //(1 or 0): promoted to front page
    $node-&gt;sticky = 0;
        if(count($values['municipios']))
        foreach($values['municipios'] as $municipio){
            if($municipio!=0){
                $node-&gt;field_municipio[LANGUAGE_NONE][]['tid']= $municipio;
            }

        }
    $node = node_submit($node); // Prepare node for saving
    node_save($node);


How can I save all the selected values into the field?

Thank you.
I think you what you want is an entity reference field.

Go the manage fields for your content type and create a new field of the type entity reference. In the setting for number of values choose unlimited and as widget choose checkboxes.

This will save the values for you, and display the chosen ones when the node is edited.