How can I use in GridView delete selected object,in Yii 2 Framework such as following image:
[enter image description here][2]
Try this
<?=Html::beginForm(['controller/bulk'],'post');?>
<?=Html::dropDownList('action','',[''=>'Mark selected as: ','c'=>'Confirmed','nc'=>'No Confirmed'],['class'=>'dropdown',])?>
<?=Html::submitButton('Send', ['class' => 'btn btn-info',]);?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'id',
],
]); ?>
<?= Html::endForm();?>
This is the controller:
public function actionBulk(){
$action=Yii::$app->request->post('action');
$selection=(array)Yii::$app->request->post('selection');//typecasting
foreach($selection as $id){
$e=Evento::findOne((int)$id);//make a typecasting
//do your stuff
$e->save();
}
}
Or Else
Follow all the steps given in this Link, You will Surely achive your goal.
Yii 2 : how to bulk delete data in kartik grid view?
https://stackoverflow.com/questions/27397588/yii-2-how-to-bulk-delete-data-in-kartik-grid-view/
You can use a column with checkboxes and bulk actions for each row selected.
Here is a related question:
Yii2 How to properly create checkbox column in gridview for bulk actions?
<?php
$url = Url::to(['user/delete']);
$this->registerJs('
$(document).on("click", "#delete_btn",function(event){
event.preventDefault();
var grid = $(this).data(\'grid\');
var Ids = $(\'#\'+grid).yiiGridView(\'getSelectedRows\');
var status = $(this).data(\'status\');
if(Ids.length > 0){
if(confirm("Are You Sure To Delete Selected Record !")){
$.ajax({
type: \'POST\',
url : \''.$url.'\' ,
data : {ids: Ids},
dataType : \'JSON\',
success : function($resp) {
if($resp.success){
alert(resp.msg);
}
}
});
}
}else{
alert(\'Please Select Record \');
}
});
', \yii\web\View::POS_READY);
?>
[1]: http://i.stack.imgur.com/iFjT1.png
I have succeeded in deleting multiple rows in gridview Yii2 by doing the following:
Create button in index.php
<p>
<button type="button" onclick="getRows()" class="btn btn-success">Delete Bulk</button>
</p>
Add javascript code in index.php to perform the event of getting the checked rows from the GridView widget.
<script>
function getRows()
{
//var user_id as row_id from the gridview column
// var list = [] is an array for storing the values selected from the //gridview
// so as to post to the controller.
var user_id;
var list = [];
//input[name="selection[]"] this can be seen by inspecting the checkbox from your //gridview
$('input[name="selection[]"]:checked').each(function(){
user_id = this.value;
list.push(user_id);
});
$.ajax({
type: 'post',
url:'index.php?r=student-detail-update/bulk',
data: {selection: list},
});
}
</script>
Put this code in your contoller
if ($selection=(array)Yii::$app->request->post('selection')) {
foreach($selection as $id){
$StudentDetailUpdates = StudentDetailUpdate::find()
->where(['user_id' => $id])
->all(); //....put your staff here
}
Related
I'm having a weird issue with ZF3.
I have a vanilla form in the view and a jquery ajax to send it to the controller, something like this:
<form>some form</form>
<script>
$("#form").submit(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "stats",
data: {name: 'TEST'} // name selected in the form
});
});
</script>
The controller for action stats looks like this:
$stat = new Stat();
$route_name = $this->params()->fromRoute('name', 'none');
$post_name = $this->params()->fromPost('name', 'none');
if(!strcmp($route_name, 'none')) // if no redirection yet
{
if(!strcmp($post_name, 'none')) // if no form was sent
{
// display the form to choose the customer
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else // if the form was sent, get name and direct to /stats/someName
{
return $this->redirect()->toRoute('stats', ['name' => 'someName']);
}
}
else // after redirection, get the name in the URL and show some data about this customer
{
return new ViewModel([
'avg_time' => $stat->get_avg_time(rawurldecode($route_name)),
]);
}
The problem is that the redirection does not occure on the screen but I still get the route parameter if I print $route_name after submitting the form.
Anyway, the goal is to have a form with a select to choose the customer name and load the customer data into /stats/[name]. Am I going in the wrong direction ? And is the redirection issue a bug or my code is wrong ?
So there I solved it thx to rkeet, this is the form & jquery:
<form id="customer_choice" method="POST" action=""> some form </form>
<script>
$("#customer_choice").submit(function () {
$("#customer_choice").attr('action', 'stats/' + $("#customer_select").val())
});
</script>
And this is the controller (hope no customer is named 'none'):
$stat = new Stat();
$name = $this->params()->fromRoute('name', 'none');
if(!strcmp($name, 'none'))
{
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else
{
return new ViewModel([
'avg_time' => $stat->get_avg_time($name),
]);
}
The result is basepath/stats/[customer name] and changing the url manually works as well.
(if you don't want changing the url manually to change the result, use fromPost instead of fromRoute)
I have following Jquery-Script, which works fine outside of yii2
<script>
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var test = $("#_id_").val();
var dataString = '_id_=' + test;
if (test == '')
{
alert("No record, no action...!");
} else
{
$.ajax({
type: "POST",
url: '<?=\Yii::$app->urlManager->baseUrl?>/insert.php',
//url: 'insert.php',
data: dataString,
cache: false,
/*
success: function (html) {
$("#display").after(html);
document.getElementById('_id_').value = '';
*/
}
});
}
return false;
});
});
</script>
It works,'cause I have following html input box:
<textarea cols="30" rows="2" style="width:480px;font-size:14px; font-weight:bold" id="_id_" maxlength="145" ></textarea>
As u can see, jquery will take id= _ id _ in order to use AJAX.
I try to realize same thing with yii2, but I get following error:
bewerber_update?id=2:1925 Uncaught TypeError: Cannot set property 'value' of null
at Object.success (bewerber_update?id=2:1925)
at fire (jquery.js:3187)
at Object.fireWith [as resolveWith] (jquery.js:3317)
at done (jquery.js:8757)
at XMLHttpRequest.<anonymous> (jquery.js:9123)
This error will be thrown out,' cause I don't konw, how to set id correctly in yii2. I tried like this, but this is obviously the wrong way:
<?=
$form->field($model, 'beurteilung_fachlich')->widget(\dosamigos\ckeditor\CKEditor::className(), [
'id'=>'_id_',
'options' => ['rows' => 1],
'preset' => 'full'
])
?>
Any ideas, how to set id in a correct way?
You should pass id in options
<?= $form->field($model, 'beurteilung_fachlich')->widget(\dosamigos\ckeditor\CKEditor::className(), [
'options' => ['rows' => 1, 'id' => '_id_'],
'preset' => 'full'
]) ?>
I do my project in yii2.
I have form which get data from db to dropdown list(using kartik depdtop widget).
First field is "type_of_goods", depending on "type_of_goods" customer receive "goods".
After they are two text input field with "goods_amount" and "total_cost" of goods depends on "goods_amount" (goods_amount * price).
Customer inputs goods amount he wants to buy, or money amount to which he wants to buy and js script shows him value in another field in both cases.
Price value is in goods table in DB.
Can I get goods_id or some information about goods from "goods"-field(to perform db query and get price and put it into js function), or maybe even price to put it into js script which do things that I wrote above.
How can I realize it? Is it right way to do it?
Code:
View
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'form-horizontal col-lg-11',
'enctype' => 'multipart/form-data'
],
]); ?>
<?= $form->field($type_of_goods, 'id')
->dropDownList(
ArrayHelper::map(Type_of_goods::find()->all(), 'id', 'name'),
['id'=>'type_of_goods_id']
);
?>
<?= $form->field($goods, 'id')->widget(DepDrop::classname(), [
'options' => ['id' => 'id'],
'pluginOptions' => [
'depends' => ['type_of_goods_id'],
'placeholder' => 'Choose your goods',
'url' => \yii\helpers\Url::to(['goods/goods-dep-type'])
]
]);
?>
<?= $form->field($goods, 'price')->textInput();
?>
<?= $form->field($order, 'amount')->textInput();
?>
<?php ActiveForm::end(); ?>
Controller:
public function actionGoodsDepType()
{
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$game_id = $parents[0];
$out = \app\models\Goods::gelGoodsList($goods_type_id);
echo Json::encode(['output' => $out, 'selected' => '']);
return;
}
}
echo Json::encode(['output' => '', 'selected' => '']);
}
Model:
public static function gelGoodsList($type_id)
{
$query = self::find()
->where(['type_id' => $type_id])
->select(['id', 'name'])->asArray()->all();
return $query;
}
public static function getPrice($id)
{
$query = self::find()
->where(['id' => $id])
->select(['price'])->asArray()->one();
return $query;
}
You would need to create an AJAX request each time user inputs new value. This might work well (place at the bottom of the view file):
$this->registerJs("
$('#Type_of_goods-price').on('change', function() { // Should be ID of a field where user writes something
$.post('index.php?r=controller/get-price', { // Controller name and action
input_price: $('#Type_of_goods-price').val() // We need to pass parameter 'input_price'
}, function(data) {
total_price = $.parseJSON(data)['result']; // Let's say, controller returns: json_encode(['result' => $totalPrice]);
$('#Type_of_goods-total').value = total_price; // Assign returned value to a different field that displays total amount of price
}
});
");
You only need to set correct elements' correct IDs and write a method in controller (using this example, it would be controller controller name and actionGetPrice method name).
I am having a paginated backend table with db-data. The admin person can filter that table for data status. This happens via ajax. Everything works fine but I do not get the selected filter value to remain selected when I click on the second pagination link.
E.g. I choose select option: '1' => 'Active' so that only db-rows show up that have a status of 1. But when I then click on the second pagination link to see the next 20 rows then again it also displays the inactive db-rows. How would I get the selected option to remain selected in this situation? I tried Input::old('status') and passing $selected to view as below but no success. Thank you for any hint!
View:
<form id="filter_form" onsubmit="" action="<?php echo URL::action('countries#anyIndex'); ?>">
<?php echo Form::select('filter_status', funcs::get_status_options(), $selected, array('id' => 'filter_status')); ?>
</form>
Ajax:
$(function(){
$("#filter_status").on('change', function(){
frm = $("#filter_form");
frm.serialize();
status = $('#filter_status').val();
$.ajax({
type: "POST",
url: $(frm).attr('action'),
data: {status: status},
success: function(data){
$("#list").html(data.list);
},
dataType: "json"
});
});
});
Controller:
class countries extends BaseController {
public $filter = array(0,1,2);
function anyIndex()
{
$data['title'] = "Countries list";
if(Input::has('status')){
$status = Input::get('status');
if($status != 2){
$this->filter = array($status);
}
}
$d['items'] = $this->_getItems(20);
if(Request::ajax()){
$data['list'] = View::make('admin/countries/countries_list', $d)->withInput($status)->render();
return Response::json($data);
}
$data['selected'] = $this->filter;
$data['list'] = View::make('admin/countries/countries_list', $d);
return View::make('admin/admin_layout')->nest('view', 'admin/countries/countries_view', $data);
}
private function _getItems($paginate)
{
$items = Country::whereIn('status', $this->filter)->paginate($paginate);
return $items;
}
}
My Telerik MVC grid is Ajax bound and I need to ability to apply custom filtering via two checkboxes (in the DIV at the top). When a checkbox is checked, the parameters would be set and the grid is reloaded. This is working fine. During the initial load the data is sorted based on the sorting settings in Telerik, but after I click a checkbox, the data is ordered by record Id and no longer by Priority. If I then hit F5 the page is reloaded and the data is sorted correct. The sorting might be a parameter for grid.rebind() or provided in OnDataBinding, but so far I have not found what I am looking for.
QUESTION: How do I specify the sorting order in the OnDataBinding or perhaps in another client event.
Here is my code:
<div style="float:right;width:600px;text-align:right">
<span>My Items <%=Html.CheckBox("newItems") %></span>
<span>Closed Items <%=Html.CheckBox("Inactive") %></span>
</div>
<% Html.Telerik().Grid<IssueModel>()
.Name("Grid")
.PrefixUrlParameters(false)
.Columns(col =>
{
col.Bound(o => o.Title);
col.Bound(o => o.Priority).Width(50).Title("Priority ID");
col.Bound(o => o.PriorityName).Width(100).Title("Priority");
col.Bound(o => o.IssueStateName).Width(100).Title("Status");
col.Bound(o => o.AssignedToName).Width(140).Title("Assigned To");
})
.DataBinding(d => d.Ajax().Select("AjaxSelect", "Ticket", new { isNew = false, isInactive = false }))
.ClientEvents(e => e.OnDataBinding("onDataBinding"))
.Sortable(s => s
.SortMode(GridSortMode.MultipleColumn)
.OrderBy(order =>
{
order.Add(o => o.Priority);
order.Add(o => o.Sequence);
})
)
.Pageable(p => p.PageSize(15))
.Filterable()
.Render();
%>
<script type="text/javascript">
function onDataBinding(e) {
e.data = {
isNew: $("#newItems").is(':checked'),
isInactive: $("#Inactive").is(':checked')
};
e.orderBy = "Severity~desc~Ranking~asc";
}
$("input[type='checkbox']").click(function () {
var grid = $('#Grid').data('tGrid');
var param = {
isNew: $("#newItems").is(':checked'),
isInactive: $("#Inactive").is(':checked')
};
grid.rebind(param);
});
</script>
I found the solution in case others need the answer. I used grid.sort() in place of grid.rebind(); The sort method takes a string in the format: column-name dash direction. Example First
<script type="text/javascript">
function onDataBinding(e) {
e.data = {
isNew: $("#newItems").is(':checked'),
isInactive: $("#Inactive").is(':checked')
};
}
$("input[type='checkbox']").click(function () {
var grid = $('#Grid').data('tGrid');
var param = {
isNew: $("#newItems").is(':checked'),
isInactive: $("#Inactive").is(':checked')
};
grid.sort("Severity-desc~Ranking-asc";);
//grid.rebind(param);
});
</script>