Having issues with hiding and showing divs on an onchange - php

I am having issues firing off an on-change in the department drop-down field not sure if i wrote it correctly. The error is Uncaught TypeError: Cannot read property 'style' of null. I am trying to select a department like claims then it will fire off an onchange to show another drop-down called workrequested. I have not filled all the departments yet but that should not mater if i want to test it on couple departments first. I think it has to do with dvPassport1.style.display
<script>
function ShowHideDiv1() {
var Department = document.getElementById("Department");
var divPassport1 = document.getElementById("divPassport1");
divPassport1.style.display = Department.value == "Claims" || Department.value == "Flat 1"|| Department.value == "Flat 2"|| Department.value == "Hanging Bulk" || Department.value == "Hanging Store North" || Department.value == "Hanging Store South" || Department.value == "Inventory Integrity" || Department.value == "Rack Shoes" || Department.value == "Fine Jewelry"? "block" : "none";
}
function ShowHideDiv2() {
var Department = document.getElementById("Department");
var divPassport2 = document.getElementById("divPassport2");
divPassport2.style.display = Department.value == "JackPotLane" ? "block" : "none";
}
</script>
<?=form_open('insert/create/', array(
'class' => 'form-horizontal',
'role' => 'form',
)); ?>
<div class="row">
<div class="container">
<h3>Validation Form</h3>
<br>
<div class="col-sm-6">
<div class="form-group">
<?php echo form_label('ZID', 'ZID', $attributes=array());?>
<?php echo form_input('ZID', set_value('ZID'), $attributes=array("class" => "form-control", "id"=>"ZID"));?>
<!--show error message -->
<div class="error"><?php echo form_error('ZID'); ?></div>
</div>
<div class="form-group">
<?php echo form_label('Employee Name', 'EmpName', $attributes=array());?>
<?php echo form_input('EmpName', set_value('EmpName'), $attributes=array("class" => "form-control", "id"=>"EmpName"));?>
<!--show error message -->
<div class="error"><?php echo form_error('EmpName'); ?></div>
</div>
<div class="form-group">
<?php echo form_label('Department', 'Department', $attributes=array());?>
<?php
$options = array(
""=>"Choose Department",
"Claims" => "Claims",
"Flat 1"=>"Flat 1");
?>
<?php echo form_dropdown('Department', $options,set_value('Department'),array("class" => "form-control", "id"=>"Department", "onchange" => "ShowHideDiv1();ShowHideDiv2();"));?>
<!--show error message -->
<div class="error"><?php echo form_error('Department'); ?></div>
</div>
<div class="form-group" id="divpassport1" style="display: none" >
<?php echo form_label('WorkRequested', 'WorkRequested', $attributes=array());?>
<?php
$options = array(
""=>"Choose WorkRequested",
"Cases Not Received" => "Cases Not Received",
"Master Pack"=>"Master Pack");
?>
<?php echo form_dropdown('WorkRequested', $options,set_value('WorkRequested'),array("class" => "form-control", "id"=>"WorkRequested"));?>
<!--show error message -->
<div class="error"><?php echo form_error('WorkRequested'); ?></div>
</div>
<div class="form-group" id="divpassport2" style="display: none" ">
<?php echo form_label('WorkRequested', 'WorkRequested', $attributes=array());?>
<?php
$options = array(
""=>"Choose jackpot WorkRequested",
"FYI" => "FYI",
"Request"=>"Request");
?>
<?php echo form_dropdown('WorkRequested', $options,set_value('WorkRequested'),array("class" => "form-control", "id"=>"WorkRequested"));?>
<!--show error message -->
<div class="error"><?php echo form_error('WorkRequested'); ?></div>
</div>
<div class="form-group">
<?php echo form_label('Description','ReqDescription', $attributes=array());?>
<?php echo form_textarea('ReqDescription',set_value('ReqDescription'),array("class"=>"form-control textarea","id"=>"ReqDescription"));?>
<!--show error ReqDescription -->
<div class="error"><?php echo form_error('ReqDescription'); ?></div>
</div>
<input type="hidden" name="DATEREQUESTED" value="<?php echo date("Y/m/d h:i:sa");?>" value="<?=set_value('DATEREQUESTED')?> " value="<?=set_value('DATEREQUESTED')?>">
<input type="hidden" class="form-control" id="Status" name="Status" value="Received" placeholder="Status" value="<?=set_value('Status')?>">
<div class="form-group">
<?php echo form_submit('submit', 'Submit', array("class"=>"btn-primary btn", "id"=>"submit"));?>
</div>
<?php echo form_close()?>

As far as I can see you want to get divPassport1 (divPassport1) and divPassport2 and not dvPassport1 and dvPassport2.
Change var dvPassport1 = document.getElementById("dvPassport1"); to var dvPassport1 = document.getElementById("divPassport1"); and second one respectively or correct the ids.
EDIT
I guess you are accessing elements too early and you DOM is not loaded yet. Move your js code to the end of page before closing body and wrap it following way to wait for window onload event:
<script>
(function() {
// your javascript code here
// the DOM will be available here
})();
</script>

Related

The right way to store data into database in a wordpress plugin

I created this plugin for a Wordpress site, in the admin page i've insert a modal that can change a specific #color in css only if it's pressed the specific color button.
With the code below, i need to reload two times the admin page for see the change, so i think it's not the correct way to insert - update values displayed. This code it's placed on the same file where modal it's declare.
Please, can you show me the wordpress right way to update or insert data into database then show the change in admin page?
Thanks.
function recensility_system_action_color_fest($id , $title, $footer )
{
global $wpdb;
$colors = $wpdb->get_results('SELECT * FROM '.$wpdb->prefix.'recensility_color_fest', ARRAY_A);
?>
<!-- The Modal -->
<div id="<?php echo $id; ?>" class="recensility-modal">
<!-- Modal content -->
<div id="<?php echo $id.'-insert'; ?>" class="recensility-modal-content">
<div class="recensility-modal-header">
<span id="<?php echo $id.'-close'; ?>" class="recensility-modal-close" onclick="close_modal('<?php echo $id; ?>')">×</span>
<h2 class="recensility-modal-title"><i class="fas fa-swatchbook"></i><?php echo $title; ?></h2>
</div>
<div class="recensility-modal-body">
<center>
<h2>Clicca sul colore da impostare</h2>
<div class="recensility-color-fest-chooser">
<form id="recensility-color-fest-form" method="post">
<div class="recensility-color-fest-chooser-body">
<div class="recensility-color-fest-chooser-items">
<?php
foreach ($colors as $color){
?>
<div class="dot-container <?php echo ($color['is_active']=='true') ? 'dot-active' : 'dot-inactive'; ?>">
<?php
echo
($color['is_active']=='true')
?
'<p class="dot-active-text">Attivo</p>'
:
'<button id="recensility-color-fest-form-submit" name="recensility-color-fest-form-submit" class="recensility-color-fest-form-button" value="'. $color['value'].'" type="submit" form="recensility-color-fest-form">';
?>
<span class="dot" style="background-color:<?php echo $color['value'] ?>"></span>
<?php echo ($color['is_active']=='false') ? '</button>' : ''; ?>
<p><?php echo $color['name'] ?></p>
</div>
<?php
}
?>
</div>
</div>
</form>
</div>
</center>
</div>
<div class="recensility-modal-footer">
<h3 class="recensility-modal-footer-content"><?php echo $footer; ?></h3>
</div>
<?php
print_r($_POST);
if (!empty($_POST['recensility-color-fest-form-submit'])){
$activeColor = ($wpdb->get_results('SELECT `value` FROM '.$wpdb->prefix.'recensility_color_fest'.' WHERE `is_active` = "true"', ARRAY_A)[0])['value'];
$wpdb->update
(
$wpdb->prefix.'recensility_color_fest',
array('is_active' => 'false'),
array('is_active' => 'true')
);
recensility_color_fest_apply($activeColor, $_POST['recensility-color-fest-form-submit']);
$wpdb->update
(
$wpdb->prefix.'recensility_color_fest',
array('is_active' => 'true'),
array('value' => $_POST['recensility-color-fest-form-submit'])
);
}
?>
</div>
</div>
<?php
}

CodeIgniter | Sometimes the user session destroyed when adding cart item

Hi im working on my workshop tools project.
Now i have some strange action sometimes when i pressed the add to cart button (mine was named pinjam) it just going back to the login page because the session destroyed. Anyone has this strange thing happened? or Can you help me?
The scenario is like this..
I pressed the add to cart button on one of much tools that can i borrow, then it post to the add_to_cart function on my controller and reload the #cart_content div on that page with new added data with jquery / ajax
Controller Siswa
function index(){
$data['guru'] = $this->model_akun->getnamaguru();
$data['data']=$this->model_alat->getAll();
$this->load->view('siswa/dashboard',$data);
}
function add_to_cart(){
if($this->model_alat->validate_add_cart_item() == TRUE){
// Check if user has javascript enabled
if($this->input->post('ajax') != '1'){
redirect('siswa'); // If javascript is not enabled, reload the page with new data
}else{
echo 'true'; // If javascript is enabled, return true, so the cart gets updated
}
}
}function show_cart(){
$this->load->view('siswa/cart');
}
Model_Alat
function validate_add_cart_item(){
$id = $this->input->post('id_alat'); // Assign posted id_alat to $id
$cty = $this->input->post('quantity'); // Assign posted quantity to $cty
//$this->db->where('id_alat', $id); // Select where id matches the posted id
$query = $this->db->query('select * from alat where id_alat="'.$id.'"')->result(); // Select the products where a match is found and limit the query by 1
//$ss = $this->input->post('ajax');
//echo $query['id_alat'];
//echo "<script>alert(".$cty.");
// </script>";
// Check if a row has been found
if($query > 0){
foreach ($query as $row){
$data = array(
'id' => $id,
'qty' => $cty,
'price' => '0',
'name' => $row->nama_alat
);
$this->cart->insert($data);
return TRUE;
}
// Nothing found! Return FALSE!
}else{
echo "<script>alert('FALSE no rows :(');</script>";
return FALSE;
}
}
JQUERY
<script>
$(document).ready(function() {
/*place jQuery actions here*/
var link = "/weteies/index.php/"; // Url to your application (including index.php/)
$("div.subalat form").submit(function() {
// Get the product ID and the quantity
var id = $(this).find('input[name=id_alat]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "siswa/add_to_cart", { id_alat: id, quantity: qty, ajax: '1' },
function(data){
// Interact with returned data
if(data == 'true'){
$.get(link + "siswa/show_cart", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
}
});
});
});
siswa/cart (for viewing the cart list)
##siswa/cart view
<div class="table-responsive">
<?php echo form_open('siswa/update_cart'); ?>
<table class="table table-bordered">
<thead >
<tr>
<th>Alat</th>
<th>Jumlah</th>
<!--<th>Total</th>-->
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php $a=0; $b=0;foreach($this->cart->contents() as $items): ?>
<tr>
<!--<input type="hidden" id="id_peminjam" name="id_peminjam" value="'.$this->session->userdata('ses_id').'"/>-->
<td><?php echo form_hidden('rowid['.$a.']', $items['rowid']);
echo $items['name']; ?></td>
<td><?php echo form_input(array('name' => 'qty['.$a.']', 'value' => $items['qty'], 'maxlength' => '2'), '', 'class="form-control form-control-sm"'); ?></td>
<!--<td><button type="button" id="'.$items['rowid'].'" class="romove_cart btn btn-danger btn-sm">Cancel</button></td>-->
<td><?php echo form_submit('', 'Update', 'class="btn btn-accept btn-sm"');
$b=$a+1;?>
</tr>
<?php $a++; endforeach; ?>
</tbody>
</table>
<?php echo form_hidden('jumlah_alat', $b);
echo form_close();?>
<?php echo form_open('siswa/sub_cart'); ?>
<table class="table">
<tr>
<td >
<select name="id_guru" class="form-control form-control-sm">
<option>Pilih Guru</option>
<?php foreach($guru as $gurus): echo '<option value='.$gurus->id_akun.'>'. $gurus->nama .'</option>'; endforeach;?>
</select>
</td>
<td>
<?php $hitung=0; $b=0; foreach($this->cart->contents() as $items): ?>
<?php echo form_hidden('id_alat'.$hitung.'', $items['id']);
echo form_hidden('jumlah_pinjam'.$hitung.'', $items['qty']);
echo form_hidden('id_siswa', $this->session->userdata('ses_id'));
$b=$hitung+1;
$hitung++;
endforeach;
echo form_hidden('jumlah_alat', $b);
echo anchor('siswa/empty_cart', 'Hapus Semua', 'class="btn btn-danger btn-sm col-sm-5"'); ?>
<?php echo form_submit('', 'Pinjam!', 'class="btn btn-primary btn-sm col-sm-5"');?>
</td>
</tr>
</table>
<?php echo form_close(); ?>
</div>
FORM siswa/dashboard
<!DOCTYPE html>
<head>
<?php $this->load->view("admin/_partials/head.php") ?>
</head>
<body id="page-top">
<!-- Navbar-->
<?php $this->load->view("siswa/_partials/navbar.php") ?>
<div id="wrapper">
<!-- Sidebar-->
<?php $this->load->view("siswa/_partials/sidebar.php") ?>
<div id="content-wrapper">
<div class="container-fluid">
<div class="row ">
<div class="col-md-6">
<div class="card mb-3">
<h4 class="card-header">Alat Tersedia</h4>
<br>
<div class="row card-body">
<?php foreach ($data as $row) : ?>
<div class="col-md-6">
<div class="card mb-3">
<div class="card-header text-center"><?php echo $row->nama_alat;?>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-7">
Tersedia
</div>
<div class="col-md-5">
<input value="<?php echo $row->jumlah;?>" class="form-control form-control-sm" readonly>
</div>
</div>
<div class="subalat">
<?php echo form_open(''); ?>
<div class="row">
<div class="col-md-7">
Mau Brp?
</div>
<div class="col-md-5">
<?php echo form_hidden('id_alat', $row->id_alat);
echo form_input('quantity', '1', 'maxlength="2" class="form-control form-control-sm"'); ?>
</div>
</div>
<br>
<?php echo form_submit('add', 'Pinjam','class="btn btn-success btn-block col-md"'); ?>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
<?php endforeach;?>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card mb-3">
<h4 class="card-header">List Pinjam</h4>
<!--<div class="card-body">-->
<div id="cart_content">
<?php $this->load->view('siswa/cart'); ?>
</div>
<!--</div>-->
<div class="card-footer small text-muted">
Jika jumlah alat nya 0(nol), alat akan dihapus. Page rendered in <strong>{elapsed_time}</strong> seconds.
</div>
</div>
</div>
</div><!-- /.row -->
</div><!-- /.content-fluid -->
<!-- Sticky Footer -->
<?php $this->load->view("siswa/_partials/footer.php") ?>
</div>
<!-- /.content-wrapper -->
</div>
<!-- /#wrapper -->
<?php $this->load->view("siswa/_partials/scrolltop.php") ?>
<!-- Modal-->
<?php $this->load->view("siswa/_partials/modal.php") ?>
<!-- Js-->
<?php $this->load->view("siswa/_partials/js.php") ?>
</body>
<script>
$(document).ready(function() {
/*place jQuery actions here*/
var link = "/weteies/index.php/"; // Url to your application (including index.php/)
$("div.subalat form").submit(function() {
// Get the product ID and the quantity
var id = $(this).find('input[name=id_alat]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "siswa/add_to_cart", { id_alat: id, quantity: qty, ajax: '1' },
function(data){
// Interact with returned data
if(data == 'true'){
$.get(link + "siswa/show_cart", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
}
});
});
});
</script>
</html>
Login controller
class Login extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model("model_login");
}
function index(){
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
if($this->form_validation->run()==FALSE){
$session = $this->session->userdata('isLoggedin');
if($session == FALSE){
$this->load->view('login');
}
else{
redirect('');
}
}
else{
$email=$this->input->post('email');
$password=$this->input->post('password');
$cek_akun=$this->model_login->auth_akun($email,$password);
if($cek_akun->num_rows() > 0){
$user_data=$cek_akun->row_array();
$this->session->set_userdata('isLoggedin',TRUE);
$this->session->set_userdata('ses_id',$user_data['id_akun']);
$this->session->set_userdata('ses_nama',$user_data['nama']);
if($user_data['level']=='admin'){ //level admin
$this->session->set_userdata('level','admin');
redirect('admin');
}
else if($user_data['level']=='aspiran'){ //level aspiran
$this->session->set_userdata('level','aspiran');
redirect('aspiran');
}
else if($user_data['level']=='guru'){ //level guru
$this->session->set_userdata('level','guru');
redirect('guru');
}
else if($user_data['level']=='siswa'){ //level siswa
$this->session->set_userdata('level','siswa');
redirect('siswa');
}
}
else{
$this->load->view('login');
echo "<script>alert('Failed Login: Check your username and password!');
</script>";
}
}
}
function logout(){
$this->session->sess_destroy();
$url=base_url('');
redirect($url);}}

Code igniter not sending select element to database and no error shows up

Im trying to send 3 ids from 3 diferent tables and 1 varchar to a table called 'session', where it will save the ids and this varchar, my problem is, everytime i click to submit, it doesnt input anything to my table, and no error shows up..
VIEW
<link href='<?php echo site_url('assets/recursos/dashboard.css');?>' rel="stylesheet">
<div class="container">
<?php echo form_open('admin/inserirsessao'); ?>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER><br>
<?php } ?>
<div class="col-xs-12">
<div class="form-group">
<label for="sel1">Filme</label>
<select name='filmes' class="form-control" id="filmes">
<?php
$id = $this->uri->segment(4);
$this->db->where('filme_id', $id);
$lista = $this->db->get('filme');
foreach($lista->result() as $row) {
?>
<option value="<?php echo $row->filme_id;?>"> <?php echo $row->Nome; ?></option>
<?php
}
?>
</select>
</div>
</div>
<h2 style="color:white; font-size:25px;">Adiciona um Filme<h2>
<div class="col-xs-12 ">
<div class="form-group">
<label for="sel1">Seleciona as Salas</label>
<select name='salas' class="form-control" id="salas">
<?php
$lista = $this->db->get('sala');
foreach($lista->result() as $row) {
?>
<option value="<?php echo $row->sala_id;?>" > <?php echo $row->description; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-xs-12">
<div class="form-group">
<label for="sel1">Seleciona tipo de filme</label>
<select name="tipofilme" class="form-control" id="tipofilme">
<?php
$lista = $this->db->get('tipo_filme');
foreach($lista->result() as $row) {
?>
<option value="<?php echo $row->tipo_filme_id;?>"><?php echo $row->tipo_filme; ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="col-xs-12">
<p style="color:white" class="text-center">Insere Hora da Sessão</p>
<div class="separator">
<?php echo form_label('Hora:'); ?> <?php echo form_error('hora'); ?>
<?php echo form_input(array('id' => 'hora', 'name' => 'hora')); ?><br />
</div>
</div>
</ul>
</li>
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?> <br/>
<?php echo form_close(); ?><br/>
</div>
</div>
</div>
CONTROLLER
public function index()
{
$this->render('admin/inseresessao');
}
public function sessao()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('hora', 'Hora', 'required');
if ($this->form_validation->run() == FALSE) {
$this->render('admin/inserirsessao');
} else {
//Setting values for tabel columns
$dadossessao = array(
'hora' =>$this->input->post('hora'),
'sala_id'=>$this->input->post('salas'),
'tipo_filme_id'=>$this->input->post('tipofilme'),
'filme_id'=>$this->input->post('filmes')
);
//Transfering data to Model
$this->insert_model1->form_insert($dadossessao);
$dadosessao['message'] = 'Dados Foram Inseridos com Sucesso';
//Loading View
$this->render('admin/inserirsessao');
}
}
}
?>
MODEL
<?php
class insert_model1 extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert( $dadossessao){
$this->db->insert('session', $dadossessao);
return $dadossessao;
}
}
?>
I've been already hours trying to fix the problem but i don't know whats happening, can someone help me?
change your form action to <?php echo form_open('inserirsessao/sessao'); ?> .

how to insert multi records in yii session using ajaxSubmitButton

I have been developing an application in Yii framework. At this point, I fall in an issue that is, I have an Order form where I select a registrant (all registrants come from database) from a dropdown, an item (all product items come from database) from dropdown and a input textbox where I type the quantity. There is a "ajaxSubmitButton" button to send all these values to the controller "actionCart" using Ajax. After receiving all values in the controller, I want to put all values in session variable. When I add another new item, the session values are being replaced what I want to hold all newly added items into the session variable. In this circumstance, what should I do. Please help me. I am giving my code snippets below:
in form:
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'order-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('class'=>'form-horizontal' , 'enctype'=>'multipart/form-data', ),
)); ?>
<div class="alert alert-info" xmlns="http://www.w3.org/1999/html">
<p class="note">Fields with <strong><span class="required">*</span></strong> are required.</p>
</div>
<?php echo $form->errorSummary($model); ?>
<div class="form-group">
<?php echo $form->labelEx($model,'registration_id', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-8">
<?php
$data = CHtml::listData(Registration::model()->findAll(),'id', 'name');
echo $form->dropDownList($model,'registration_id',$data,array('class' => 'form-control chzn-select','prompt'=>'Select a Registrant'));
?>
</div>
<?php echo $form->error($model,'registration_id'); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'item', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-8">
<?php
$data = CHtml::listData(Products::model()->findAll(),'id', 'name');
echo $form->dropDownList($model,'item',$data, array('class'=>'form-control chzn-select' , 'id'=>'item', 'prompt'=>'Select an Item')); ?>
<?php
?>
</div>
<?php echo $form->error($model,'item'); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'quantity', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-2">
<?php
echo $form->textField($model,'quantity',array('class' => 'form-control','size'=>60,'maxlength'=>11));
?>
</div>
<?php echo $form->error($model,'quantity'); ?>
</div>
<div class="form-group">
<div class="col-lg-8 pull-right">
<?php
echo CHtml::ajaxSubmitButton('Add to Cart',Yii::app()->createUrl('admin/order/cart'),
array(
'type'=>'POST',
'update'=>'#cartResult',
),
array('class'=>'btn btn-primary btn-sm',));
?>
</div>
</div>
<div class="form-group">
<div id="cartResult" class="col-lg-12">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
In controller:
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$productId = $item["item"];
$quantity = $item["quantity"];
$quantity = $item["quantity"]=='' ? 1 : $item["quantity"];
$productInfo = Products::model()->findByPk(array('id'=>$productId));
$totalPrice = $productInfo->price * $quantity;
$session = Yii::app()->session;
$session['cart'] = array("product_id" => "$productId" , "product_name" => "$productInfo->name", "quantity" => "$quantity","price" => "$productInfo->price");
}
}

How do I use ajax/jquery in yii to add rows to another table and use these values as foreign key in a form?

I have this form (I used crud generator and model generator):
Create Pig
[Name]
[Breed]
[Sickness] [Add sickness]
How do I make add sickness create a new textfield everytime I click it? I already have a table for the multivalued sicknessid, I just need to access that table and add all the sicknesses, use one same id so I can use it as foreign key in the table.
<?php
/* #var $this PigController */
/* #var $model Pig */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'pig-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->dropDownList($model,'name');?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'breed'); ?>
<?php echo $form->dropDownList($model,'breed', $model- >getBreedOptions()); ?>
<?php echo $form->error($model,'breed'); ?>
</div>
/*
ENTER CODE FOR SICKNESS HERE
*/
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I also had the same scenario. What i have done is with script.
Try this. It worked for me. Please do make necessary changes
$(function(){
$("#add").click(function(){
if(5 > $(".attr").length) {
var cycleBlock = '<tr id="item'+i+'">';
cycleBlock += '<td style="width: 447px;"> <label for="CategoryMstExt_Attribute">Attribute</label> <input type="text" id="CategoryMstExt_0_attributes" name="CategoryMstExt['+i+'][attributes]" class="attrName'+i+'" maxlength="100" size="44"> </td> <td> <label for="CategoryMstExt_Data_Type">Data Type</label> <select id="CategoryMstExt_'+i+'_datatype" name="CategoryMstExt['+i+'][datatype]" class="attr" onchange="javascript:checkSelection(this.value,'+i+')"> <option value="17">Textarea</option> <option value="16">Textbox</option> <option value="18">Listbox</option> </select><img onclick="deleteElm(item'+i+'.id);" src="<?php echo Yii::app()->request->baseUrl; ?>/assets/81ff99cf/gridview/delete.png" alt=""> </td>';
cycleBlock += '</tr>';
var $cycleBlock = $(cycleBlock);
$('#fields').append($cycleBlock);
i++;
} else {
alert('Maximum attributes limit reached');
}
});
});
<?php
<img style="margin-left:600px;" id="add" src="<?php echo Yii::app()->request->baseUrl; ?>/media/images/add.png">
<table id="fields" >
<tr id="item1" >
<td style="width: 447px;">
<?php echo $form->labelEx($model, 'Attribute'); ?>
<?php echo $form->textField($model, '[0]attributes', array('size' => 44, 'maxlength' => 100, 'class' => 'attrName0')); ?>
</td>
<td >
<?php echo $form->labelEx($model, 'Data Type'); ?>
<?php echo $form->dropDownList($model, '[0]datatype', Array('17' => 'Textarea', '16' => 'Textbox', '18' => 'Listbox'), array('onChange' => 'javascript:checkSelection(this.value,0)', 'class' => 'attr')); ?>
<img onclick="deleteElm(item1.id);" src="<?php echo Yii::app()->request->baseUrl; ?>/media/images/delete_2.png" alt="">
</td>
</tr>
</table>
?>

Categories