问题
So, I'm having a real hard time with Select2. I want users to be able to search through a select list and also create new tags when no search result is found. Creating new tags is not the problem. The main thing - and surprisingly overlooked in most forums - is to INSERT the news tags to the Database. I'm new to Select2, so I'd like to have a full example. And I'm using PHP on this project, so, if there is a way to do this with PHP it would be really helpful.
Here is my code:
$('#caracteristicas').select2({theme:'bootstrap', width:null, placeholder:'Selecione', allowClear:true})
<?php
$q = mysqli_query($con, "select id, descricao from caracteristicas");
if(mysqli_num_rows($q)>(0))
{
?>
<div class="form-group">
<label for="caracteristicas">Selecione um ou mais resultados</label>
<select name="caracteristicas[]" id="caracteristicas" class="form-control" multiple="multiple">
<option value="">Selecione</option>
<?php
while($linhas = mysqli_fetch_array($q)):
?>
<option value="<?=$linhas["id"]?>">
<?=strlen($linhas["descricao"])>50 ? substr($linhas["descricao"], 0, 50)."..." : $linhas["descricao"]?>
</option>
<?php endwhile;?>
</select>
</div>
<?php } mysqli_close($con);?>
Note: I'm using Select2 4.0
回答1:
Just figured out how to do this. I've noticed that tags created by user don't have an id, wich means, the option value will be a string, instead of a number. So, all I had to do was tell PHP to handle string values in a different way. Here's how I solved this:
for($i=0; $i<count($opcoes); $i++)
{
if(!is_numeric($opcoes[$i]))
{
if(!mysqli_query($con, "INSERT INTO `atividades`(`id`, `descricao`) VALUES (NULL, '".$opcoes[$i]."')"))
{
$msg_caracteristicas[$i] = "A atividade não foi cadastrada, <strong>erro <a href='http://randomurl.com' target='_blank'>#".mysqli_errno($con)."</a></strong> - \"".mysqli_error($con)."\"";
}
else
{
echo "<script>alert('deu certo');</script>";
}
}
}
来源:https://stackoverflow.com/questions/37836584/how-to-create-new-tags-with-select2-and-save-to-database