Check box as a header in yajra datatable - javascript

is it possible set checkbox as header in yajra datatable using addColumn function.
->editColumn('message', function ($data) {
return '' . $data->message . '';
})
In edit column, first argument is string('message'string as header). I want check box as header using addColumn in yajra datatable.

In Datatable
private function getColumns()
{
return [
'id' => ['name' => 'id', 'data' => 'id', 'style' => 'width:90%' , 'class'=>'msg']
];
}
Edit Column
->editColumn('id', function ($data) {
return '<input type="checkbox" class="group-checkable" value="'.$data->id.'">';
})
In Blade:
<script>
var htmlstr = '<input type="checkbox" id="checkAll"/> ';
$('.msg').html(htmlstr)
</script>
Make Orderable false in datatable
$this->getColumns(),
[
'id' => [
'orderable' => false,
'searchable' => false,
'printable' => false,
'exportable' => false,
'class'=>'msg',
]
]

Related

select 2 widget validation with j query in yii2?

so i have written a code for select field and i am using yii2 here is my code
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), ['data'
=> $listData,
'options' => ['placeholder'=>'Select', 'multiple' =>
false,'required'=>true], 'pluginOptions' => ['tags' => false, 'tokenSeprators'
=> [',', ' '], 'maximumInputLength' => 20], ],])->label(false); ?>
i want to validate it by using jquery validate plugin i have tried so far validation rules
$('form').validate({
errorClass:'help-block help-block-error',
errorPlacement: function(error, element) {
if(element.attr("name") == "TestModel[primaryfield]" )
{
error.insertAfter(".error_message2");
}
else
error.insertAfter(element);
},
rules: {
'TestModel[email]': {
required:true,
email: true
},
'TestModel[name]':
{
required:true,
},
'TestModel[primaryfield]':
{
required:true
}
},
my email and name getting validated but select2 field(primary field is not getting validate ) i want to apply validation rules only if anyone can give me solutions
With Yii2, You just declare rules in Model. Then,
In your template, enable "enableClientValidation" option of AcitveForm as below:
<?php $form = \kartik\form\ActiveForm::begin([
'enableClientValidation' => true,
'options' => [
'id' => 'ajax-contact-form'
]
]); ?>
With Select2 Widget, it's not enough. So I have to using javascript as below:
$(document).ready(function () {
$("select").on("select2:close", function (e) {
if (!$(this).val()) {
var formGroup = $(this).parent().parent();
formGroup.addClass('has-error');
$('.help-block:first', formGroup).html('Please choose one partner!')
}
});
});
Here is the result on form:
My select2 HTML structure:

Yii2 Javascript fail to print

This is my form field.
As can see, there is a div tag with details id right below the form field. I wanted to print the content inside the div tag out whenever I select the contact.
$url2 = yii\helpers\Url::toRoute('op-client/contact');
$this->registerJs($this->render('script2.js'), \yii\web\VIEW::POS_READY);
$form->field($model, 'contact_id')->widget(Select2::classname(), [
'data' => $getcontact,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' =>
[
'change' => 'function()
{
var contactid = $(this).val();
getDetails(contactid);
"'.$url2.'"
}',
],
]).'
<div id="details">
</div>
Script2.js
function getDetails(contactid,url2)
{
var csrfToken = $('meta[name="csrf-token"]').attr("content");
console.log(contactid);
$.ajax({
type:"POST",
cache:false,
url:url2,
data:{contactid:contactid, _crsf:csrfToken},
success:function(data){
$("#details").html(data);
//document.getElementById("details").innerHTML = data;
},
})
}
Controller
public function actionContact()
{
$request = Yii::$app->request;
$contact = $request->post('contactid');
$contacts =OpContact::find()
->where(['id'=>$contact])
->one();
echo $contacts->name;
}
The problem seems like I cant print out the contact name. I can get the correct contact id but I cant print out the name inside the div tag, it just show blank onchange. Is there anything wrong with my calling method? Thanks

Symfony2 cascasing dropdown value change via ajax not accepting on submission

I have two entity dropdowns field in my symfony form. On the front end i change the option list of 2nd drop drown using ajax based on the value of first dropdown selected value. and Upon submitting the form i get the error that,
This value is not valid.
below is the code;
/**
* #ORM\ManyToOne(targetEntity="State")
* #ORM\JoinColumn(name="province_id", referencedColumnName="id")
*/
protected $Province;
/**
* #ORM\ManyToOne(targetEntity="District")
* #ORM\JoinColumn(name="district_id", referencedColumnName="id")
*/
protected $District;
and in the form,
->add('domicileDistrict','entity', [
'label' => ucwords('District'),
'class'=>'GeneralBundle\Entity\District',
'required' => true,
'mapped' => true,
'attr' => ['class' => 'form-control'],
'label_attr' => ['class' => 'control-label'],
])
->add('domicileProvince','entity', [
'label' => ucwords('Province'),
'class'=>'GeneralBundle\Entity\State',
'required' => true,
'attr' => ['class' => 'form-control select2'],
'label_attr' => ['class' => 'control-label'],
])
and on front end,
$("#profile_from_type_domicileProvince").change(function() {
var state = $('option:selected', this).val();
getDistrictByState(state);
});
function getDistrictByState(state){
var dict = {
type: "POST",
url: "{{ url('ajax_district_by_stateId') }}?id=" + state,
success: function(e) {
$("#profile_from_type_domicileDistrict option").remove();
$.each(e, function(e, p) {
$("#profile_from_type_domicileDistrict").append($("<option />", {
value: e,
text: p
}));
});
}
};
$.ajax(dict);
}
UPDATE: Add PRE_SUBMIT Event;
After suggestion form #Alsatian, I update my form and add the event as below, but nothing happens on selecting first dropdown.
$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'preSubmitData']);
public function preSubmitData(FormEvent $event){
$form = $event->getForm();
$data = $event->getData();
if (array_key_exists('Province', $data)) {
$state = $data['Province'];
$event->getForm()
->add('District','entity', [
'label' => ucwords('District'),
'class'=>'GeneralBundle\Entity\District',
'required' => true,
'mapped' => true,
'query_builder' => function(DistrictRepository $repository) use ($state) {
$qb = $repository->createQueryBuilder('d')
->andWhere('d.verified = :verified')
->andWhere('d.active = :active')
->setParameter('verified', true)
->setParameter('active', true);
if ($state instanceof State) {
$qb = $qb->where('d.state = :state')
->setParameter('state', $state);
} elseif (is_numeric($state)) {
$qb = $qb->where('d.state = :state')
->setParameter('state', $state);
} else {
$qb = $qb->where('d.state = 1');
}
return $qb;
},
'attr' => ['class' => 'form-control select2'],
'label_attr' => ['class' => 'control-label'],
]);
}
}
I had the same problem.
I wrote a bundle here to deal with "extensible" choice types (also entity or document) :
https://github.com/Alsatian67/FormBundle/blob/master/Form/Extensions/ExtensibleSubscriber.php
How I do it :
Hooking in the form submission process, we can access to the submitted entity by the PRE_SUBMIT FormEvent.
All submitted entity are loaded and are in $event->getData().
Then we have just to take this submitted choices as new 'choices' option for the field.
Caution :
Doing it so it will only validate that the entity submitted exist !
If only a part of the entities are possible choices you have to add a constraint to validate them.
You can also set the choices in the PRE_SUBMIT event, depending on the value of the first dropdown (instead of using all submitted entities).

How to get value of checked gridview column

Hi guys i have a gridview like below
and i want to get the 'user_id' of the checked column
how can i do that???
I could easily get the checked column id but i dont know how to get data of those checked column in gridview
i want to get it via javascript so that i can pass it to service
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'showOnEmpty'=>true,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
[
'attribute' => 'event_id',
'label' => 'Event Title',
'value' => 'event.title'
],
[
'attribute' => 'user_id',
'label' => 'Email',
'value' => 'users.email',
],
'user_type',
],
]);
?>
and here is my javascript to get ids of checked column
jQuery(document).ready(function() {
btnCheck = $("#send");
btnCheck.click(function() {
var keys = $("#w0").yiiGridView("getSelectedRows");
}
});
Let me tell you the flow of this
On homepage is a gridview like this
Now user will click on that small user sign and that will open the page you can see below
Thats when i want to send messages to all selected users
Because in my case title is from different table and name and email are from different table so i want ids of user table
For that i want user_id but i am getting some random values
What can i do here???
I tried this but its returning some random string
public function search($params)
{
if(!isset($_GET['id'])){
$id='';
}
else{
$id=$_GET['id'];
}
$query = Checkin::find()->where(['event_id'=> $id]);
$query->joinWith(['event', 'users']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'created_date' => $this->created_date,
'created_by' => $this->created_by,
'updated_date' => $this->updated_date,
'updated_by' => $this->updated_by,
]);
$query->andFilterWhere(['like', 'user.email', $this->user_id]);
$query->andFilterWhere(['like', 'user_type', $this->user_type]);
$dataProvider->keys ='user_id';
return $dataProvider;
}
Update your DataProvider set $dataProvider->keys ='userId' then you will able to get all keys of user_id
data-id of GridView and get allSelectedColumns
You need to just replace this code
['class' => 'yii\grid\CheckboxColumn'],
with below code
[
'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => function($data) {
return ['value' => $data->user_id];
},
],

Using alternate DataSource column if empty

I'm using YUI2 databases. I have my columns specified like so:
var columns = [
{ key: "check"
, label: '<input type="checkbox" name="checkAll" id="checkAll"/>'
, formatter: "checkbox"
}
, { key:"subject"
, sortable:false
, resizeable:false
, formatter: YAHOO.widget.DataTable.formatSubject
, width: "16px"
} .....more
Datasource:
var mySource = new DataSource('.do?');
mySource.responseType = DataSource.TYPE_JSON;
mySource.responseSchema = {
resultsList : 'records',
fields : [
'pos'
,'subject'
,'subject2' ....
In my datasource I return 'subject' for each row along with another column, lets call it 'subject2'. I want the 'subject' column to use 'subject2' from the datasource when the 'subject' column for that specified row is blank. Is this possible without overwordly hacks?
The easiest way I think is to just use a formatter:
YAHOO.widget.DataTable.formatFrom = function ( elCell, oRecord, oColumn, oData ) {
var val = oData;
if(val === "") {
val = oRecord.getData().subject2;
}....

Categories

Resources