Я использую Codeigniter и Mysql. Я пытаюсь отправить несколько выпадающих значений флажка в таблицу mysql. Но только 1 ценность будет стоить. Последнее значение относится к базе данных. Я пробовал и другие методы. Но в конце концов я здесь. Заранее спасибо.
Вот вид.
<div class="form-group">
<select class="form-control" data-toggle="dropdown"></select>
<ul class="dropdown-menu">
<li>
<a href="#" name="sub_cat_id" id="sub_cat_id" class="small" data-value="option1" tabIndex="-1">
<input name="sub_cat_id" id="sub_cat_id" type="checkbox"/ ><?php echo $this->lang->line('select_sub_cat_message')?>
</a>
</li>
</div>
<script>
$(document).ready(function(){
$('#item-form').validate({
rules:{
name:{
required: true,
minlength: 4,
remote: {
url: '<?php echo site_url("items/exists");?>',
type: "GET",
data: {
name: function () {
return $('#name').val();
},
sub_cat_id: function() {
return $('#sub_cat_id').val();
}
}
}
},
unit_price: {
number: true
}
},
messages:{
name:{
required: "Please fill item Name.",
minlength: "The length of item Name must be greater than 4",
remote: "Item Name is already existed in the system"
},
unit_price: {
number: "Only number is allowed."
}
}
});
$('#cat_id').change(function(){
var catId = $(this).val();
$.ajax({
url: '<?php echo site_url('items/get_sub_cats');?>/'+catId,
method: 'GET',
dataType: 'JSON',
success:function(data){
$('#sub_cat_id').html("");
$.each(data, function(i, obj){
// $('#sub_cat_id').append('<option value="'+ obj.id +'">' + obj.name + '</option>');
$('#sub_cat_id').append('<input name="sub_cat_id" type="checkbox" value="'+ obj.id +'"/> ' + obj.name + '');
});
$('#name').val($('#name').val() + " ").blur();
}
});
});
$('#sub_cat_id').on('change', function(){
$('#name').val($('#name').val() + " ").blur();
});
$(function () { $("[data-toggle='tooltip']").tooltip(); });
});
</script>
Вот настройка контроллера
function add()
{
if(!$this->session->userdata('is_shop_admin')) {
$this->check_access('add');
}
$action = "save";
unset($_POST['save']);
if (htmlentities($this->input->post('gallery'))) {
$action = "gallery";
unset($_POST['gallery']);
}
if ($this->input->server('REQUEST_METHOD')=='POST') {
$item_data = array();
foreach ( $this->input->post() as $key=>$value) {
$item_data[$key] = htmlentities($value);
}
$item_data['shop_id'] = $this->get_current_shop()->id;
$item_data['is_published'] = 1;
//unset($item_data['cat_id']);
if ($this->item->save($item_data)) {
$this->session->set_flashdata('success','Item is successfully added.');
} else {
$this->session->set_flashdata('error','Database error occured.Please contact your system administrator.');
}
if ($action == "gallery") {
redirect(site_url('items/gallery/'.$item_data['id']));
} else {
redirect(site_url('items'));
}
}
$cat_count = $this->category->count_all($this->get_current_shop()->id);
$sub_cat_count = $this->sub_category->count_all($this->get_current_shop()->id);
if($cat_count <= 0 && $sub_cat_count <= 0) {
$this->session->set_flashdata('error','Oops! Please create the category and sub category first before you create items.');
redirect(site_url('items'));
} else {
if($cat_count <= 0) {
$this->session->set_flashdata('error','Oops! Please create the category first before you create items.');
redirect(site_url('items'));
} else if ($sub_cat_count <= 0) {
$this->session->set_flashdata('error','Oops! Please create the sub category first before you create items.');
redirect(site_url('items'));
}
}
$content['content'] = $this->load->view('items/add',array(),true);
$this->load_template($content);
}
Вот функция модели
function save(&$data, $id = false)
{
if (!$id && !$this->exists(array('id' => $id, 'shop_id' => $data['shop_id']))) {
if ($this->db->insert($this->table_name, $data)) {
$data['id'] = $this->db->insert_id();
return true;
}
} else {
$this->db->where('id', $id);
return $this->db->update($this->table_name, $data);
}
return false;
}
Изменить 1 Забыл проверить очевидность, проверьте это в представлении
<a href="#" name="sub_cat_id"
id="sub_cat_id"
class="small" data-value="option1"
tabIndex="-1">
<input name="sub_cat_id" id="sub_cat_id" type="checkbox"/ >
<?php echo $this->lang->line('select_sub_cat_message')?>
</a>
U имеет одинаковое имя для тегов <a>
и <input>
.
____________________________________________________________________
Вы отправляете это на сервер
<input name="sub_cat_id" id="sub_cat_id" type="checkbox"/> <?php echo $this->lang->line('select_sub_cat_message')?> </a>
Проблема здесь в том, что name="sub_cat_id"
это строка, и вам нужен массив, один из способов решить это - переименовать имя в name="sub_cat_id[]"
, а для его получения в вашей функции контроллера u можете использовать
function functionThatProcessesTheForm(){
$subCatIds = $this->input->post('sub_cat_id');
/**
subCatIds its an array, the value of each element will be
the "value" the input had, if it wasn't selected, it will not be
contained in the array
**/
}
Важный
Задайте значение, если входное value ="theidvalue"
, если u не id не достигнет контроллера, и u найдет такой массив, как [1,1,1,1,1,1]
если значения установлены, массив ur будет [id1,id2,id3,...,idn]
Надеюсь, мой ответ вам поможет.
mk_items
( name
, cat_id
, sub_cat_id
, discount_type_id
, unit_price
, formulation
, item_form
, packing
, search_tag
, description
, shop_id
, is_published
) VALUES («Веб-разработчик», «3», NULL, «14», «155», «das», «fdsfs», «165», «das», «fsdf sf», «1», 1) Имя файла: E: \ xampp5 \ htdocs \ usamapharmacy \ m- admin \ system \ database \ DB_driver.php Номер строки: 330
<input type="checkbox" name="sub_cat_id" />
?, Оставив для него что-то вроде <input type="checkbox" value="someCatId" name="sub_catr_id">
name
, поэтому будет отправлен только последний.