I'm trying to put a value from javascript into a form action in Yii2
is it possible?
More specifically I need to make a URL change for each option that is selected in a dropdownList.
form in views/site.php
$form = ActiveForm::begin([
'id' => 'form',
'method' => 'POST',
'action' => Url::to(['programas/'.Tours::findOne(['pk' => ])->programa]),
]);
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList([],
[
'prompt' => 'Programa',
'id' => 'child1_child2',
'onchange' => 'updateValue(this.value)',
]
)->label(false); ?>
Js file
function updateValue(val){
x = document.getElementById("test").value;
// document.getElementById("form").action = "programas/";
}
So, I rescue the value from the selected option with JS but I need to put it in here 'pk' => 'value'
where value is the #child1_child2 selected option value.
'action' => Url::to(['programas/'.Tours::findOne(['pk' => ])->programa])
Thanks for the help.
You can use one of the following approach with some modification:
//pk => programa
$data = [
1 => 'programa1',
2 => 'programa2',
3 => 'programa3',
];
1) Use JS
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, ['prompt' => 'Programa'])->label(false); ?>
JS
$this->registerJs('
$("#dropdownID").change(function() {
var text = $("#dropdownID option:selected").text();
$("#formID").attr("action", "/pathtoproject/programas/" + text);
});
', \yii\web\View::POS_END);
2) Use Ajax Call
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, [
'prompt' => 'Programa',
'onchange'=> '$.get( "'.Url::toRoute('get-action').'", { id: $(this).val() } )
.done(function( data ) {
$("#formID").attr("action", data);
}
);'
])->label(false); ?>
Controller
public function actionGetAction($id)
{
$name = Tours::findOne(['pk' => $id])->programa];
echo \yii\helpers\Url::to(['programas/'.$name]);
}
Related
I have code to get some data (terms = page-a) built with Wordpress.
Currently, the data of page-a is acquired like'terms' =>'page-a' and displayed on the example.com/page-a page.
I would like to change this data acquisition code so that the data along the lower page url can be acquired (for example, the data on page-b at example.com/page-b).
I created a code to get the url with $_SERVER and convert it, but I can't get the url because I am using ajax. I want to get the url with javascript and pass it to php.
How should I make the changes?
functions.php
add_action('wp_ajax_get_case', 'dk_get_case');
add_action('wp_ajax_nopriv_get_case', 'dk_get_case');
function dk_get_case() {
$headers['Access-Control-Allow-Origin'] = '*';
$return = ['status' => false, 'data' => [], 'message' => ''];
$case_clinics = [1,2,3,4];
foreach($case_clinics as $key => $case_clinic){
// (1)Get the current URL
$http = is_ssl() ? 'https' : 'http' . '://';
$url = $http . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
// (2)Get a string such as'page-a' from the URL
$keys = parse_url($url);
$path = explode("/", $keys['path']);
$terms = $path[2];
$dk_posts = get_posts(
array(
'showposts' => -1,
'post_type' => 'case',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'case_clinic',
'field' => 'term_id',
'terms' => $case_clinic
),
array(
'taxonomy' => 'case_category',
'field' => 'slug',
'terms' => 'page-a'
)
)
)
);
taxonomy-case_category-page-a.php
<div class="col case-right">
<h3 style="font-family:'Futura PT'; font-weight:600">Clinic</h3>
<h4 style="font-weight:600">Clinic</h4>
//data display position
<div class="case-img" data-slider-3></div>
<div class="popup"></div>
</div>
Tried
footer.php
<script>
jQuery(document).ready(function () {
var url = window.location.href;
$.ajax({
type: "GET",
url: "taxonomy-case_category-page-a.php",
data: {"url": url},
});
});
taxonomy-case_category-page-a.php
<?php var_dump($_GET['url']); ?>
error
GET: 404error
https://example.com/pagea/taxonomy-case_category-page-a.php?url=https%3A%2F%2Fcharme-beauty.jp%2Fstaging%2Fcase%2Fpagea%2F
I have a problem to connect two select. I would like the choice of a select filters the search of the second select statement.Both select take data from their tableDB but are not influenced each other. Can someone help me?
my first select customers take data from db table customers:
<?=
Html::dropDownList('userlist', [],
ArrayHelper::map(Customers::find()->where('id',['company_id' =>
'name'])->orderBy('name')->all(), 'id', 'name'),
['prompt' => 'Select a User ...',
'class' => 'form-control',
'style' => 'width: 100%;']);
?>
my second select offers take data from db table offers:
<?=
Html::dropDownList('offerslist', [],
ArrayHelper::map(Offers::find()->where('customer_id',['company_id'
=> 'offers_n'])->orderBy('customer_id')->all(),
'id','offers_n','customer_id'),
['prompt' => 'Select a Offert ...',
'onchange' => 'change_user_list(this.value)',
'class' => 'form-control',
'style' => 'width: 100%;']);
?>
This is my function js:
function change_user_list(company_id)
{
$.ajax({
url: "<?= \yii\helpers\Url::to(['offers/userlist'])?>",
type: 'get',
data: {
company_id: company_id
},
success: function (data) {
document.getElementsByName('userlist')[0].innerHTML = data;
}
});
}
this is my actionFucntion in the controller:
public function actionUserlist($company_id)
{
if (Yii::$app->request->isAjax) {
$userlist = ArrayHelper::map(Customers::find()-
>where(['company_id' => $company_id])->orderBy('name')->all(),
'id', 'name');
$string = "<option value>Select a Users</option>";
foreach($userlist as $id => $name) {
$string .= "<option value=".$id.">".$name."</option>";
}
return $string;
}
}
I have a dropdown menu, that has a onchange function. Once the function is executed it changes another dropdown menu.
I need to make it so it executes the script onload.
1st dropdown:
echo $form->field($model, 'company_id')->dropDownList($items_company, ['prompt' => 'Select Company', 'style' => 'width:400px;', 'onchange' => '
$.post("index.php?r=project/lists&id=' . '"+$(this).val(), function( data ) {
$( "select#project-client" ).html( data );
console.log("On change");
console.log(data);
});
',])->label('Company');
2nd dropdown:
echo '<label class="control-label">Company Client</label>';
echo Select2::widget([
'model' => $model,
'attribute' => 'client',
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [ 'label' => 'Client',
'multiple' => true, 'style' => 'width:400px;', 'overwriteInitial' => true],
'pluginOptions' => [
'disabled' => false,
],
]);
This is what I tried:
$(document).ready(function () {
var currentProjectCompany = $('#project-company_id').val();
$.post("index.php?r=project/lists&id=' . '" + currentProjectCompany, function (data) {
$("select#project-client").html(data);
console.log("Company ID:");
console.log(currentProjectCompany);
console.log("Clients");
console.log(data);
});
});
Move the onchange code into its own function (it should be there anyway), and execute that function in the ready() function.
That way it will fire both onchange and onload.
I do the same check my code it may help you .But i use ajax and jquery.
For firs dropdown .
echo $form->dropDownListGroup(
$model 'id', array(
'wrapperHtmlOptions' => array(),
'widgetOptions' => array(
'data' => abc::getName($model->id),
'htmlOptions' => array(
'prompt' => 'Select Project',
'ajax' => array(
'type' => 'POST',
'url' => ( Yii::app()->createUrl('/' . $domain_name . '/qq/xyz/abc') ),
'update' => '#seconddropdownid',
//'dataType' => 'json',
'data'=>array('id'=>'js:this.value'),
)
),
),
)
);
in second dropdown :
echo $form->dropDownListGroup(
$project, 'tag', array(
'wrapperHtmlOptions' => array(),
'widgetOptions' => array(
'data' =>$this->getProjectTags(),
'htmlOptions' => array(
'prompt' => 'Select Tags',
),
)
)
);
on change of the second list you can update the the list-view of yii .
i have two tables user and department where department has two fields id and name i want to create a view so that when someone selects a department name from the dropdownlist the user's name of all in that department show in another dropdownlist using AJAX and How to call that in controller
<script>
jQuery(document).ready(function ($) {
//jQuery('#searchTable').dataTable();
$('#department_id').change(function () {
jQuery('#user').empty();
var data2 = {};
data2['department_id'] = jQuery(this).val();
var json = JSON.stringify(data2);
jQuery.ajax({
type: "POST",
url: "/AjaxRequests/name",
data: json,
dataType: "json",
success: function (response) {
var app = "<option value>All</option>";
jQuery('#user').append(app);
jQuery.each(response, function (i, text) {
jQuery('#user').append(jQuery('<option></option>').val(i).html(text));
});
}
});
});
</script>
this is the script i am using
and in view the department dropdown is like this
<?php echo $this->Form->input('department_id', array('onChange' => 'showFields(this.value)', 'class' => 'form-control-custom', 'id' => 'department_id', 'type' => 'select', 'label' => true, 'label' => 'department:', 'options' => $departments, 'empty' => 'Select A Department', 'required' => 'false'))
?>
Anyone please help me with this ajax and also the controller
According to your code, can u try to replace 'id' => 'department' with 'id' => 'department_id' . Cause it's seen here you are using department_id as selector but your department_id id as not declared in dropdownlist. Here you declared department as ID. So selector is not found. So Just replace 'id' => 'department' with ''id' => 'department_id'', Hope it can be helpful to you.
I am using Yii2 modal to update a form in modal window but I am unable to fetch the values to be already filled in the form.
In this screen-shot link below:
http://awesomescreenshot.com/0f957qq367
When I click on edit option, It takes me to the update form which is opened in a modal window. But this form shows empty values in all fields. I want to update the form.
Please find this in this screen-shot below:
http://awesomescreenshot.com/0f257qqscb
This is the snippet for what I have tried yet:
<?php
use yii\bootstrap\Nav;
use yii\bootstrap\Modal;
Modal::begin([
'id'=>'modalEdit',
//'header' => '<h2>Hello world</h2>',
'size'=> 'modal-lg',
//'toggleButton' => ['label' => 'click me'],
]);
$newmodel = new Backlog();
// $newmodel->id;
echo $this->render('/backlog/update', ['model' => $newmodel]);
Modal::end();
echo Nav::widget([
'options' => ['class' => 'nav-pills navbar-right'],
'encodeLabels' => false,
'items' => [
['label' => '', 'items' => [
['label' => '<span data-toggle="modal" data-target="#modalEdit" style="cursor: pointer;">Edit</span>','url' => 'javascript:void(0);'],
'<li class="divider"></li>',
['label' => '<span>Assign</span>', 'url' => ['#']],
'<li class="divider"></li>',
['label' => '<span>Convert To Backlog</span>', 'url' => ['#']],
'<li class="divider"></li>',
['label' => '<span>Close</span>', 'url' => ['#']],
]],
],
]);
if Backlog is an ActiveRecord Replace the Line with this.
$newmodel = Backlog::findOne(['ID'=>$id]);
Finally, I solved the problem using javascript and ajax loading :
$(document).on("click",".edit-backlog",function(e){
var back_l_id=$(this).attr("b-id");
var modal_body=$("#modalEdit").find(".modal-body");
$.ajax({
url:getAjaxUrl('backlog','update'),
data:{'id':back_l_id},
success:function(res){
//console.log(res);
modal_body.html(res);
}
});
});
I added a class .edit-backlog to span and get the id ("b-id") and used in the above script. Hope this answer helps others too.