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
Related
How do you target the sub-fields inside a repeater field, so the JS applies to the sub-field when appending new groups???
Been looking, but I got really lost as to where even to start. And the JavaScript API is falling a little short on explaining how to work with repeaters.
I'm working on a form to add orders for a bakery. The form has a repeater which holds the options for each different bread order. In here the select field for TYPE OF DOUGH does much of the pre-selection for the other fields (size, shape, extras).
I've managed to target the select field of TYPE OF DOUGH to send and modify data through AJAX, but when adding another repeater row the code doesn't work.
Here's my code for php and js.
JS
jQuery(document).ready(function ($) {
// field key for TYPE OF DOUGH select field inside repeater field
var field = acf.getField("field_609b103fcd576");
field.on("change", function (e) {
var value = field.val();
console.log(value);
var data = {
"action": "get_size_options",
"type_of_dough": value,
};
$.ajax({
url: ajax_object.ajax_url,
type: "post",
data: data,
dataType: "json",
success: function (data) {
console.log(data);
},
});
});
});
PHP
// enqueue the scripts
function fw_acf_register_scripts() {
// enqueue js file with ajax functions
wp_enqueue_script(
'acf-ajax-script',
get_template_directory_uri() . '/assets/js/autopopulate.js',
['jquery']
);
wp_localize_script(
'acf-ajax-script',
'ajax_object',
['ajax_url' => admin_url('admin-ajax.php')]
);
}
add_action('acf/input/admin_enqueue_scripts', 'fw_acf_register_scripts');
// ex. function to get options for the other fields
function get_size_options() {
$meta_value = fw_get_term_id($_POST['type_of_dough'], 'dough');
// just a function to get the ID for the taxonomy from the slug,
// so it just returns a number, say 501 which is then used for the term query
$size_options = array();
$terms_args = array(
'taxonomy' => 'size',
'hide_empty' => false,
'meta_key' => 'tax_position',
'orderby' => 'tax_position',
'order' => 'ASC',
);
if ($meta_value_masa) {
$terms_args['meta_query'] = array(
array(
'key' => 'dough',
'value' => $meta_value,
'compare' => 'LIKE',
),
);
}
$terms = get_terms($terms_args);
foreach ($terms as $term) {
$size_options[$term->term_id] = $term->name;
}
wp_send_json($size_options);
die();
}
add_action('wp_ajax_get_size_options', 'get_size_options');
I'm trying to create an AJAX action in elgg. I have followed this Elgg tutorial: Ajax: Performing actions, but I'm getting nothing so far, apart from the fail error:
Sorry, Ajax only!
The other error is that the page reloads, instead of persisting the data asynchronously.
What am I getting wrong? Thank you all in advance.
Below is my code:
form: views/default/forms/service_comments/add.php
<?php
$url_confirm = elgg_add_action_tokens_to_url("action/service_comments/add?guid={$guid}");
$params_confirm = array(
'href' => $url_confirm,
'text' => elgg_view_icon('upload'),
'is_action' => true,
'is_trusted' => true,
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
?>
<div class="update-options">
<?= $confirm ?>
</div>
start.php
elgg_register_action("service_comments/add", __DIR__ . "/actions/service_comments/add.php");
action file: actions/service_comments/add.php
<?php
elgg_ajax_gatekeeper();
$arg1 = (int)get_input('arg1');
$arg2 = (int)get_input('arg2');
// will be rendered client-side
system_message('We did it!');
echo json_encode([
'sum' => $arg1 + $arg2,
'product' => $arg1 * $arg2,
]);
Javascript : views/js/service_comments/add.js
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
You have written ajax procedure but not invoking it. Instead you are directly calling it . by making it link.
$params_confirm = array(
'href' => '#',
'text' => elgg_view_icon('upload'),
'onclick' => "myajax_function()",
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
Then move your JS code inside a function.
function myajax_function(){
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
}
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).
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];
},
],
I have a GridView displaying employee payslips, and beside each of their names are check boxes. Refer to the picture below:
As you can see, I also have a drop-down list. I set it in my jQuery to select the last child of the list which is my case, the April 10, 2015 - April 16, 2015 option. On page load, I can see this page (photo above) with those check boxes. I had a problem with the check boxes since when I click the header check box, it should select all of the check boxes below it. But it's not. Now, when I tried selecting another option in the drop-down list, here's what I get:
The style of the check boxes changes. And now, when I check the header check box, it's already working, selecting every check boxes below.
Here's how I display the drop-down list:
echo Select2::widget([
'name' => 'period',
'data' => $period,
'options' => [
'placeholder' => 'Select period',
'id' => 'period',
'style' => 'width: 400px; height: 34px;'
],
'pluginOptions' => [
'maximumInputLength' => 10,
],
]);
GridView:
<?php \yii\widgets\Pjax::begin(['id' => 'employee']); ?>
<?php
echo GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn',
'options' => ['class' => 'icheckbox_minimal',]
],
'fname',
'lname',
'totalEarnings',
'totalDeductions',
'netPay',
[
'label' => 'Action',
'content' => function ($model, $key, $index, $column) {
if ($model->netPay != null) {
return Html::a('View Payslip', ['view' , 'id' => $model->payslipID], ['class' => 'btn btn-success']);
}else{
return Html::a('Create Payslip', ['create-new', 'id' => $model->user_id], ['class' => 'btn btn-warning']);
}
}
]
],
]);
?>
<?php \yii\widgets\Pjax::end(); ?>
Script:
<script>
$(document).ready(function(){
$("#period option:last-child").attr('selected', 'selected');
$("#period").change( function()
{
var period = $('#period').val();
if(period != 0){
$.ajax({
url: 'index.php?r=payslip/periods',
dataType: 'json',
method: 'GET',
data: {id: period},
success: function (data, textStatus, jqXHR) {
$.pjax.reload({container:'#employee'});
//alert(data.start);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
}
}
);
})
</script>
My question is, how do I preserve/maintain the style of the check boxes? And why does it change in style? And why are the styled check boxes not working?
Your checkboxes are changed with javascript to look like that.
You have 2 problems:
1) your "check all" function works just fine, you just need to refresh the status of the checkboxes afterwards. It works like this: when you click on the div that replaces the checkbox then the checkbox gets changed under it. Your problem is that you check it with the scripts so you need to trigger the div that sits on top of it to change too.
2) because you use pjax your page DOM gets changed. However because you probably change the checkboxes on "onload" of the page the new checkboxes remain unstyled. You need to run the function that changes them again after the pjax call.