How to make a value array with select Multiple

Asked

Viewed 613 times

0

Scenario is as follows, I have a select Multiple with the options of the type of activity of each person registered in the system, however the same person can be a client and an employee, but when serializing the form with jquery I am receiving several variables from my select.

let form = $('#form-pessoas-cadastrar').serializeArray();
console.log(form);

resultado do console.log(form)

$.post('/api/pessoas/store',form); // Só salva o ultimo valor "atividades[]=5"

My problem is in this part, I cannot serialize select to save the values in the same column of the database pessoas.atividades('1,3,5') then I also have to do the reverse, bring the values of the bank pro select.

  • How were the activities defined in the database ? What is the structure of the table(s) related(s) ?

  • @Isac mysql, varchar(10).

  • And how I would keep the various values in one varchar(10)? Not to mention that this modeling is not correct because it will create difficulties later in relating activities with employees/customers

  • what you suggest?

  • If each client and/or employee can serve several activities then the correct modeling would be to create a separate table that associates client/employee with activity. This however is not directly related to the problem indicated in the question

1 answer

0


I was able to solve the problem by adjusting html, and dealing with jquery as follows.

// Alterei o source html/pug com os valores legíveis de cada atividade.
label.col-md-1.control-label Atividades
div.col-md-2
select.form-control(multiple='', style="width: 100%", name='atividades_temp')
  optgroup(label='Atividades')
    option(value='Cliente') Cliente
    option(value='Proprietário') Proprietário
    option(value='Colaborador') Colaborador
    option(value='Transportador') Transportador
    option(value='Armazenador') Armazenador

// seletor jquery do select atividades_temp
let $atv = $("select[name='atividades_temp']");

// Usei um input para alocar as informações vindas do select atividades_temp
$('input.select2-search__field').attr({name: 'atividades', type: 'hidden'});

// no evento OnClick do botão submit eu pego o array do multiple select 
// e adiciono no input hidden, para serializar o form.
$("input[name='atividades']").val($atv.val().toString());            
console.log($atv.val().toString()); // "Cliente,Proprietário,Colaborador,Transportador"
let form = $('#form-pessoas-cadastrar').serializeArray();
$.post(urlApi, form);

Summary:
A select multiple create an array with the selected options, but the function toString() js transforms the array object into a string object, so I can slice and treat as needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.