I have a table: Users with 3 different attributes:
ID
firstname
lastname
In the index.ctp page for Users, for each data entry, I have the Edit action available to use.
<div>
<table class="usersTables" id="userTable">
<thead>
<tr>
<th scope="col"><?= $this->Paginator->sort('firstname') ?></th>
<th scope="col" class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?= h($user->firstname) ?></td>
<td class="actions">
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $user->id], ['class' => 'view', 'data-id' => $user->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script type="text/javascript">
$(function () {
$('.edit').click(function () {
ev.preventDefault();
var userId = $(this).attr('data-id');
$('#editModal').modal('show');
alert(userId);
});
});
</script>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="editModalLabel">Edit</h4>
<div>
<div class="col-sm-6">
<?= $this->Form->input('firstname', ['class' => 'form-control', 'label' => 'First Name', 'placeholder' => 'First name', 'id' => 'firstname']); ?>
</div>
<div class="col-sm-6">
<?= $this->Form->input('lastname', ['class' => 'form-control', 'label' => 'Last Name', 'placeholder' => 'Last name', 'id' => 'lastname']); ?>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="savebutton" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
Clicking the Edit button in the table first gives me an alert pop up that tells me which $user->id I selected, then opens up the Edit modal. However, my form inputs are still empty even though the related attributes for that specific datat entry are fileld in the database. I'm not sure how to connect the data-id variable that was then defined as a JavaScript variable to the form input which I believe requires a PHP variable again ($user->firstname).
If I use 'value' => $user->firstname in the firstname form input, I get the data from the very last data entry every time (eg. if I have 3 data entries in my Users table, I will always get the 3rd entry's firstname).
Glad you researched about AJAX. First you need to create a function in your controller that will return a user's details.
// Just an example in the UsersController
public function userDetails($id = null) {
$userDetails = $this->Users->find('all'['where(['id' => $id])])->first();
$this->set(array(
'output' => $userDetails,
'_serialize' => 'output',
'_jsonp'=>true
));
}
Then setup an ajax request from your view.
// in your index.ctp's script
<script type="text/javascript">
$(function () {
$('.edit').click(function () {
ev.preventDefault();
var userId = $(this).attr('data-id');
$('#editModal').modal('show');
$.ajax({
url:"localhost/your_project/Users/userDetails/"+userId+".json",
type:'POST',
success:function(res) {
console.log(res); // check the response in your console
if(res) {
$('#firstname').val(res.firstname);
$('#lastname').val(res.lastname);
}
}
});
});
});
You can send the userId as a post data for the function's parameter.
Related
Is there someone who can help me with the following?
I use a modal/form to edit a model onscreen, and update the model via Pjax. Saving is no problem, but now the gridview must be updated with Pjax as well.
For my modal I use the following code
<?php
$form = ActiveForm::begin(
['enableClientValidation' => true, 'options' => ['id' => $model->formName()]]);
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><?= $actionTitle ?> <?= StringHelper::basename(get_class($model)); ?></h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<?php echo Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<?php ActiveForm::end();
$this->registerJs(<<<JS
$(document).on('hidden.bs.modal', function (e) {
$(e.target).removeData('bs.modal');
});
JS
);
?>
<?php $script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e){
var \$form = $(this);
$.post(
\$form.attr("action"), //Serialize Yii2 Form
\$form.serialize()
).done(function(result){
if(result == true){
$(\$form).trigger("reset");
$(document).find('#modalphysicalcomponent').modal('hide');
$.pjax.defaults.timeout = false;
$.pjax.reload({container:'#Grid'});
}else{
$("#message").html(result.message);
}
}).fail(function(){
console.log("server error");
});
return false;
});
JS;
$this->registerJs($script);
?>
It should update only the following gridview, but instead reloads the entire page which results in an error as certain POST variables are not resend.
<?php Pjax::begin(['id' => 'Grid']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'component.tag',
'component.name',
'component.parent.tag',
[
'label' => 'Configure',
'format'=>'raw',
'value' => function ($model, $key, $index, $column){
return Html::a('Configure '.get_class($model), ['update-modal', 'id' => $model->component->id], ['data-toggle'=>'modal', 'data-target'=>'#modalphysicalcomponent' ,'class' => 'btn btn-xs btn-primary', ]);
}
],
],
]); ?>
<?php Pjax::end(); ?>
I use the same modal on a different page, and it seems to work fine there, but I can't spot any differences between the two view pages.
Anyone who can help?
You need to pass the grid id as text, and not object when reloading the gridview. The object is passed as the second parameter which are the options.
This is your mistake
$.pjax.reload({container:'#Grid'});`
it should be like below
$.pjax.reload('#Grid');
See the docs for the Pjax here
hello guys i have a problem with my ajax data json, i have a project about scan a barcode with a webcam but it just views the code of the barcode, the data in the database not call in my ajax, this is the code of blade, i'm using a modal
this is the modal
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="scanModalLabel">Scan Barcode</h5>
<button type="button" class="close close-btn" data-dismiss="myModal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<dl class="row">
<dt class="col-sm-4"><h4>Kode Barang</h4></dt>
<dd class="col-sm-8" id="kode_barang"></dd>
</dl> <hr>
<table class="table align-items-center tabel-detail" >
<thead class="thead-light">
<tr>
<th>Nama Barang</th>
<th>Harga Jual</th>
<th>Stok</th>
<th>Insert</th>
</tr>
</thead>
<tbody class="list">
</tbody>
</table>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
this is the jquery code
var args = {
autoBrightnessValue: 100,
resultFunction: function(res) {
[].forEach.call(scannerLaser, function(el) {
$(el).fadeOut(300, function() {
$(el).fadeIn(300);
});
});
scannedImg.attr("src", res.imgData);
scannedQR.text(res.format + ": " + res.code);
console.log(res.code);
document.getElementsByName('qrcode')[0].value = res.code;
var kode= res.code;
$('#kode_barang').text(': '+kode);
$.ajax({
url:"{{ route('daftar_produk.scan') }}",
method:'GET',
data:{kode:kode},
dataType:'json',
success:function(data)
{
$('.list').html(data.table_data)
}
});
$('#myModal').modal('show');
},
this is the controller
public function cekScan(Request $req)
{
$id = $req->get('kode');
$output='';
$produk = Produk::findOrFail($id)
->where('kode_barang', '=', $id)
->select('produks.*')
->first();
$no = 0;
$data = array();
foreach ($produk as $list) {
$no ++;
$output .= '<tr><td>'.$no.'</td><td>'.$list->nama_barang.'</td><td>'."Rp.".format_uang($list->harga_jual).'</td><td>'.$list->stok.'</td><td><a type="button" data-stok=(('.$list->stok.')) data-id=(('.$list->id.')) data-nama=(('.$list->nama_barang.')) data-kode=(('.$list->kode_barang.')) data-harga=(('.$list->harga_jual.')) class="btn btn-primary btn-pilih" role="button">Insert</a></td></tr>';
}
$data = array(
'table_data' => $output
);
return json_encode($data);
}
this is the route
Route::get('transaksi/scan', '\App\Http\Controllers\ProdukController#cekScan')->name('daftar_produk.scan');
what should i do the error said "jquery.min.js:2 GET http://localhost:8080/rezkastore1/%7B%7B%20route('daftar_produk.scan')%20%7D%7D?kode=2135758676 404 (Not Found)"
Seems like problem with URL.
You can't access the route in JS file.
Make a global variable in blade for ajaxURL then use in JavaScript.
<script>
var ajaxURL = '{{ route('daftar_produk.scan') }}';
</script>
<script src="xyz.js"></script>
I have no idea wether you write your Javascript section, in Laravel Blade View or in separate JS file. If you write it within Laravel Blade Template, you may use
$.ajax({
url:"{{ route('daftar_produk.scan') }}",
but I recommend you to write complete URL within your AJAX call. Make your AJAX call like this :
$.ajax({
url:"/transaksi/scan",
method:'GET',
data:{kode:kode},
dataType:'json',
success:function(data) {
$('.list').html(data.table_data)
}
});
Instead of using findOrFail(), you can use find() or regular where() with error handler, because findOrFail() will returns 404 not found if it can't find any records, here is the cekScan function
public function cekScan(Request $req)
{
$id = $req->get('kode');
$output='';
$produk = Produk::where('kode_barang', '=', $id)->first();
if (!$produk) {
return json_encode(['table_data' => 'Barang Tidak Ditemukan']);
}
$no = 0;
$data = array();
foreach ($produk as $list) {
$no ++;
$output .= '<tr><td>'.$no.'</td><td>'.$list->nama_barang.'</td><td>'."Rp.".format_uang($list->harga_jual).'</td><td>'.$list->stok.'</td><td><a type="button" data-stok=(('.$list->stok.')) data-id=(('.$list->id.')) data-nama=(('.$list->nama_barang.')) data-kode=(('.$list->kode_barang.')) data-harga=(('.$list->harga_jual.')) class="btn btn-primary btn-pilih" role="button">Insert</a></td></tr>';
}
$data = array(
'table_data' => $output
);
return json_encode($data);
}
Maturnuwun
My target is, after I submit the form, there'll be a modal after reload that shows the transaction details. I have made a next page transaction details, however, it is much better to do the receipt php on onload modal after submission. But I don't know how to start. I provided a screenshot below of my current work. Any help will be appreciated. Thank you
View:
<button type="button" data-id="<?php echo $rows->userID; ?>" data-firstname="<?php echo $rows->firstname; ?>" class=" showmodal btn btn-success btn-sm text-bold " data-toggle="modal" data-target="#fundModal"><i class="fas fa-hand-holding-usd mr-1"></i> FUND </button> // This button shows modal when clicked
//This is my modal for transferring fund
<div class="modal fade" id="fundModal" tabindex="-1" role="dialog">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-header bg-green">
<h5 class="modal-title text-bold" id="exampleModalLabel">Fund</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body bg-white text-center">
<label><h3>Transfer fund:</h3></label>
<br>
<!-- FORM -->
<div id="errorMessage" style="color: red; display: none; font-size: 11px"></div>
<form method="POST" action="<?php echo site_url('network/form_validation');?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<input type="hidden" id="firstname" name="receiptname" value="<?php echo $rows->firstname; ?>">
<div class="col-lg-12" >
<input type="text" placeholder="Enter Amount" name="amount" autocomplete="new-amount" value="" class="form-control number" id="box" >
<br>
<?php echo $this->session->flashdata('warning'); ?>
<input type="password" placeholder="Enter Password" autocomplete="new-password" name="fundpass" class="form-control" id="password" required ">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Controller:
public function form_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$this->load->library('form_validation');
$this->form_validation->set_rules('fundpass', 'fundpass', 'callback_password_check');
if($this->form_validation->run() == false) {
echo '<script>alert("Invalid input of Password!");</script>';
redirect('network/agents', 'refresh');
}
else {
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$fname = $this->input->post('receiptname');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
$this->networks->insert_data($data1);
// return json_encode($data1);
$_SESSION["amount"] = $this->input->post("amount");
$_SESSION["receivedID"] = $id;
$_SESSION["receiptFName"] = $fname;
$_SESSION["reference"] = $this->input->post("refNumber");
redirect(base_url() . "network/receipt");
}
else
{
$this->index();
}
}
}
public function password_check($fundpass)
{
$id = $this->session->userdata('uid');
if($this->session->userdata('password')!== md5($fundpass)) {
$this->form_validation->set_message('password_check', 'The {field} does not match');
return false;
}
return true;
}
Model:
function fundin($data)
{
// Fund in
$id = $this->input->post('userID');
$sqlInsertLedger = "INSERT INTO transaction_ledger (transactionSource, transType, refNumber, userID, amount, currentBalance, previousBalance, remarks, createdBy)
select '".$data['transactionSource']."', '".$data['transType']."', '".$data['refNumber']."', ".$data['userID'].", ".$data['amount'].", sum(TU.currentPoints + ".$data['amount'].") as totalPoints, TU.currentPoints,
'funded by agent', '".$this->session->userdata('uid')."'
from users TU where TU.userID=?";
$Q = $this->db->query($sqlInsertLedger, $data['userID']);
//update user table
$sqlUpdate = "update users set currentPoints = currentPoints + ? where userID = ?";
$Q = $this->db->query($sqlUpdate, array($data['amount'], $data['userID']));
}
function insert_data($data1)
{
// fund out
$sql1 = "select * from transaction_ledger where userID = ? order by ledgerID desc limit 0,1";
$Q1 = $this->db->query($sql1, $data1['userID']);
$R1 = $Q1->row_array();
$ref= $this->session->userdata('userID') + time ();
$idata1 = array(
'userID' => $data1['userID'],
'transactionSource' => 'FR',
'transType' => 'out',
'refNumber' => 'FO' . $ref,
'amount' => $data1['amount'],
'currentBalance' => $R1['currentBalance'] - $data1['amount'],
'previousBalance' => $R1['currentBalance'],
'remarks' => 'transfer fund to agent',
);
$this->db->insert('transaction_ledger', $idata1);
$sqlUpdate = "update users set currentPoints = '".$idata1['currentBalance']."', dateUpdated = '".date('Y-m-d h:i:s')."'where userID = ?";
$this->db->query($sqlUpdate, $idata1['userID'] );
}
You can programmatically open the bootstrap modal when document ready
Just like
$(document).ready(function(){
$("#fundModal").modal('show');
});
</script>
I would suggest to do with ajax call for better user experience.
$( "#formId" ).on('submit', function(e){
e.preventDefault();
let $form = $(this);
$.post( 'post-url-here', $form.serialize(), function(result) {
var result = JSON.parse(result);
if( result.status == 'success' ) {
$("#fundModal").modal('show');
}
});
});
I'm generating table rows with data from a database.
Below is my code:
<table class="table table-hover" id="dashEventTable">
<thead>
<tr>
<th>Created at</th>
<th>Seminar Name</th>
<th>Quota</th>
<th>Location</th>
<th>Option</th>
<th style="display:none"></th>
</tr>
</thead>
<tbody script="javascript">
<?php
$one = 1;
$Lihat="SELECT * FROM event where status = '$one'";
$Tampil = mysqli_query( $db, $Lihat );
while ( $hasil = mysqli_fetch_array ( $Tampil ) ) {
$id_event = ( $hasil['id_event'] );
$nama_event = ( $hasil['nama_event'] );
$lokasi = ( $hasil['lokasi'] );
$kuota = ( $hasil['kuota'] );
$created_at = ( $hasil['created_at'] );
{ ?>
<tr>
<td class="created_at"><?php echo date( 'Y-m-d h:i a', strtotime( $created_at ) ); ?></td>
<td class="event_name"><?php echo "$nama_event"; ?></td>
<td class="kuota"><?php echo "$kuota"; ?></td>
<td class="lokasi"><?php echo "$lokasi"; ?></td>
<td>
<a class="btn btn-xs btn-danger btn_delete" data-toggle="modal" href="#deleteDashEvent"><i class="fa fa-trash"></i></a>
</td>
<td class="event_id" style="display:none"><?php echo "$id_event"; ?></td>
</tr><?php }
} ?>
</tbody>
</table>
Now when I click on the button inside the rows, it does two things, the first is going to this JavaScript function:
$( ".btn_delete" ).click(function() {
var $row = $( this ).closest( "tr" ); // Find the row
var event_id = $row.find( ".event_id" ).text();
console.log( event_id );
$.ajax({
url: "contain_data.php",
method: 'post',
data: {
'send': event_id
},
success: function() {
alert( event_id );
}
});
});
From the alert and console log, I saw that I got the correct ID for the event id of the row. The data will then be sent to the PHP file above, and inside that PHP is this:
<?php
if ( isset( $_POST['send'] ) ) {
$id_event = $_POST['send'];
} else {
echo "The data has not been received!";
}
The second thing it does is go to this div for the delete confirmation:
<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
<div class="modal fade" id="deleteDashEvent">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Delete Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this event?</p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
<button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
</div>
</div>
</div>
</div>
</form>
When the DELETE button is clicked, it will then go to this PHP file:
<?php
session_start();
include( "config.php" );
if ( isset( $_POST['admin_delete_event'] ) ) {
include( "contain_data.php" );
$zero = 0;
$delete_query = "UPDATE event, jadwal_acara, waktu_pendaftaran
SET event.status = '$zero', jadwal_acara.status = '$zero', waktu_pendaftaran.status = '$zero'
WHERE event.id_event = '$id_event'
AND jadwal_acara.id_event = '$id_event'
AND waktu_pendaftaran.id_event = '$id_event'";
if ( mysqli_query( $db, $delete_query ) ) {
$delete = "Data has been deleted";
echo $delete;
} else {
echo "Error: " . $delete_query . "<br>" . mysqli_error( $db );
}
} else {
echo "The button is not detected!";
}
The problem I am having is that I received this error when I click the delete confirmation button:
The data has not been received!
Undefined variable: id_event in...
Which means that I fail in sending the data.
What am I doing wrong and how can I resolve it?
EDIT: after adding error handling to the php file, the value sent by the ajax is null instead of the id_event, do you guys know why?
Update your AJAX With:
$.ajax({
url: "contain_data.php",
method: 'post',
data : 'send='+event_id,
success:function(){
alert(event_id);
}
});
try to pass your event_id using this way
data : 'send='+event_id,
because you have taken
method: 'post',
Hope it will help
I got your error . Upto submit your first form through is correct when you go for delete conformation you miss that event_id and you just using that one in you "admin_delete_event.php" file that why it giving error
Undefined variable: id_event in...
Now just add an hidden input field in form and submit it then the event_id will be available to you.
<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
<div class="modal fade" id="deleteDashEvent">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Delete Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this event?</p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
<button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
</div>
</div>
</div>
</div>
<input type="hidden" name='event_id' value='id' id='event'>
</form>
And just change this in your 1st Ajax
$( ".btn_delete" ).click(function() {
var $row = $( this ).closest( "tr" ); // Find the row
var event_id = $row.find( ".event_id" ).text();
console.log( event_id );
$.ajax({
url: "contain_data.php",
method: 'post',
data: {
'send': event_id
},
success: function() {
$('#event').val(event_id);
alert( event_id );
}
});
});
Then it will work fine.
I'm trying to validate CActiveForm on modal dialog. I use bootstrap.
The problem is modal dialog. When I read the contents of form during the load of main html page JavaScriopt validation works, but when I load the contents on click of button, validation scrips are gone.
Here is the view of calling page
<?php
/* #var $this SiteController */
$this->pageTitle=Yii::app()->name . ' - Все магазины';
$this->breadcrumbs=array(
'Shops',
);
$jsCreate = "$(\".createShop\").click(function(){
var target = $(this).attr('data-target');
var url = '?r=site/editShop';
$(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('create-shop-script',$jsCreate,CClientScript::POS_READY);
$jsEdit = "$(\".editShop\").click(function(){
var target = $(this).attr('data-target');
var url = $(this).attr('href');
$(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('edit-shop-script',$jsEdit,CClientScript::POS_READY);
$jsDelete = "$(\".deleteShop\").click(function(){
var target = $(this).attr('data-target');
var url = $(this).attr('href');
$(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('delete-shop-script',$jsDelete,CClientScript::POS_READY);
?>
<h2>Все объекты</h2>
<!-- I created separate dialog for shop and warning because on open it shows the previous content while forming the new one
and I don't want to show shop elements on warning and vise versa -->
<!-- modal dialog for shop -->
<div id="shopModal" class="modal fade" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
</div>
</div>
<!-- modal warning dialog -->
<div id="warningModal" class="modal fade" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
</div>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Название <span class="hidden-xs">объекта</span></th>
<th><span class="glyphicon glyphicon-ok visible-xs" data-toggle="tooltip" title="Статус активности"></span><span class="hidden-xs">Статус</span></th>
</tr>
</thead>
<?php foreach($shops as $shop) :?>
<?php $disabled = ($shop->active) ?'' :'gray'?>
<tr>
<td><span class="<?php echo $disabled; ?>"><?php echo $shop->name; ?></span></td>
<td>
<?php echo ($shop->active) ?"<span data-toggle='tooltip' title='Активен' class='glyphicon glyphicon-eye-open'></span>" :"<span data-toggle='tooltip' title='Неактивен' class='glyphicon glyphicon-eye-close'></span>" ?>
<a data-toggle='modal' data-target='#shopModal' class="editShop" href="?r=site/editShop&id=<?php echo $shop->id; ?>"><span data-toggle='tooltip' title='Редактировать объект' class="glyphicon glyphicon-edit"></span></a>
<a data-toggle='modal' data-target='#warningModal' class="deleteShop" href="?r=site/deleteShop&id=<?php echo $shop->id; ?>"><span data-toggle='tooltip' title='Удалить объект' class="glyphicon glyphicon-remove-circle"></span></a>
</td>
</tr>
<?php endforeach; ?>
</table>
<button style='float:right;' data-toggle='modal' data-target='#shopModal' class="createShop btn btn-primary"><span data-toggle="tooltip" title="Добавить объект"><span class="glyphicon glyphicon-plus"></span> <span class="hidden-xs">Добавить объект</span></span></button>
This is the view of form, that appears inside modal dialog
<?php
/*
#var $this SiteController
#var $form CActiveForm */
?>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'shop-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
'htmlOptions'=> array('class'=>'bottom0',),
'action'=>"$url&id={$model->id}",
));?>
<div class="modal-content panel-primary">
<div class="modal-header panel-heading">
<button type="button" class="close panel-title" data-dismiss="modal" aria-hidden="true"><span data-container="body" data-toggle="tooltip" title="Закрыть">×</span></button>
<h4 class="modal-title panel-title"><?php echo $title;?></h4>
</div> <!-- end modal-header -->
<div class="modal-body">
<div class="form-group">
<?php echo $form->textField($model,'name',array('data-toggle'=>'tooltip', 'title'=>'Название', 'class'=>'form-control', 'placeholder'=>'Название', 'maxlength'=>'50')); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="form-group">
<label data-toggle="tooltip" title="Статус активноси">
<?php echo $form->checkBox($model,'active') .' '. $form->label($model,'active') . $form->error($model,'active'); ?>
</label>
</div>
</div> <!-- end modal-body -->
<div class="modal-footer">
<!-- Save button -->
<button type="submit" class="btn btn-primary"><span data-toggle="tooltip" title="Сохранить"><span class="glyphicon glyphicon-ok"></span> <span class="hidden-xs">Сохранить</span></span></button>
<!-- Cancel button -->
<button type="button" class="btn btn-default" data-dismiss="modal"><span data-toggle="tooltip" title="Отменить"><span class="glyphicon glyphicon-remove"></span> <span class="hidden-xs">Отменить</span></span></button>
</div> <!-- end modal-footer -->
</div>
<?php $this->endWidget(); ?>
This is my Shops model
<?php
/**
* This is the model class for table "shops".
*
* The followings are the available columns in table 'shops':
* #property integer $id
* #property string $name
* #property string $active
*/
class Shops extends CActiveRecord
{
public function tableName()
{
return 'shops';
}
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name', 'length', 'max'=>255),
array('active', 'length', 'max'=>1),
array('id, name, active', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array();
}
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'Name',
'active' => 'Active',
);
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
This is my site controller that deals with shop create/update/delete
public function actionEditShop($id=null)
{
if (!$this->checkAuthenticated()) return;
if(isset($_POST['ajax']) && $_POST['ajax']==='shop-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$model = $this->loadShop($id);
if(isset($_POST['Shops']))
{
// create/update shop
$fields = $_POST['Shops'];
$fields['id'] = $id;
$model->attributes=$fields;
if($model->save())
$this->redirect(array('shops'));
} else {
// open form to create/update
$this->renderPartial('classifier',array('model'=>$model, 'title'=>'Объект', 'url'=>'?r=site/editShop'), false, true);
}
}
public function actionDeleteShop($id, $confirmed=null)
{
if (!$this->checkAuthenticated()) return;
$model = $this->loadShop($id);
if (isset($confirmed)){
$model->delete();
$this->redirect(array('shops'));
} else {
$this->renderPartial('warning',array('url'=>"?r=site/deleteShop&id=$id&confirmed=1",));
}
}
private function loadShop($id=null)
{
if ($id){
$model=Shops::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,"Объект под номером $id не существует.");
} else {
$model = new Shops; // creates with active='1'
$model->active = '1';
}
return $model;
}
You need to explicitly tell your controller to include your scripts using the processOutput parameter of renderPartial(). When set, processOutput() is called which:
Postprocesses the output generated by render(). This method is invoked
at the end of render() and renderText(). If there are registered
client scripts, this method will insert them into the output at
appropriate places. If there are dynamic contents, they will also be
inserted. This method may also save the persistent page states in
hidden fields of stateful forms in the page.
You should also uncomment
$this->performAjaxValidation($model);
and look at Yii renderpartial (proccessoutput = true) Avoid Duplicate js request if you use processOutput.