how to show result of jquery in another form element? - javascript

I have following method:
public function actionBaustein($textId) {
$text = PaTextbaustein::findOne($textId)->data;
Yii::$app->response->format = Response::FORMAT_JSON;
return $text;
}
and following elements in formular:
<?=
$form->field($model, 'textbaustein_id')->widget(\kartik\widgets\Select2::classname(), [
'data' => \yii\helpers\ArrayHelper::map(\backend\models\PaTextbaustein::find()->where(['angelegt_von' => Yii::$app->user->identity->id])->orderBy('id')->asArray()->all(), 'id', 'beschreibung'),
'options' => ['placeholder' => Yii::t('app', 'Textbaustein selektieren'),
'id' => 'bez',
],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
///////////////////////////////////////////////////////////////////////////////////////////////
<?=
$form->field($model, 'vorlage', ['addon' => [
'prepend' => ['content' => 'Vorlage']]])->textarea(['id' => 'cke_Text', 'rows' => 22, 'format' => 'html', 'disabled' => true])
?>
If I will slect one element of id 'bez' using following code:
$script = <<< JS
$('#bez').change(function(){
var textId=$(this).val();
alert('Der Inhalt des Records der ID:'+textId+' wird in das Feld übernommen. Kopieren Sie ihn ggf. in das Feld -Vorlage-');
$.get('baustein',{textId:textId},function(data){
$('#cke_Text').val(data);
});
});
JS;
$this->registerJS($script);
....I will get following error:
XHRGEThttp://localhost:1025/Yii2_PsychoApp/backend/web/index.php/pa-mail/baustein?textId=1
[HTTP/1.1 403 Forbidden 256ms]
GET
http://localhost:1025/Yii2_PsychoApp/backend/web/index.php/pa-mail/baustein?textId=1
Status
403
Forbidden
VersionHTTP/1.1
Übertragen897 B (62 B Größe)
Referrer Policystrict-origin-when-cross-origin
How to fix this error?

Thx a lot toward ScaisEdge. In actual fact, I ddidn't have any permission io order to
carry out actionBaustein. Now, following error will be thrown out:
Server error 500: Missing parameter textID
Why? I give this parameter in Controller
Got solution at my own:
After using var_dump(), I got it:
public function actionBaustein($textId) {
$text = PaTextbaustein::findOne($textId)->content;
Yii::$app->response->format = Response::FORMAT_JSON;
return $text;
}

Related

how will I append data I am selecting from a dropdown list to the next input field in yii2

I want to select courses from the course field, then let it show in my courses field and submit the courses to the database. or if someone can help me so my courses can appear has a checkbox and once i tick a checkbox, it appears in the courses field
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'student_id') ?>
<?=
$form->field($model, 'faculty_id')->dropDownList(
ArrayHelper::map(Faculties::find()->asArray()->all(), 'faculty_id', 'faculty_name'), [
'prompt' => 'Select Faculty',
'onchange' => '$.post("' . Yii::$app->urlManager->createUrl('/departments/lists?id=') . '"+$(this).val(), function(data) {
$("select#registrations-department_id").html (data);
});'
]
);
?>
<?=
$form->field($model, 'department_id')->dropDownList(
ArrayHelper::map(Departments::find()->asArray()->all(), 'department_id', 'department_name'), [
'id' => 'registrations-department_id',
'prompt' => 'Select Department',
'onchange' => '$.post("' . Yii::$app->urlManager->createUrl('/courses/lists?id=') . '"+$(this).val(), function(data) {
$("select#registrations-course_id").html (data);
});'
]);
?>
<?=
$form->field($model, 'course_id')->dropDownList(
ArrayHelper::map(Courses::find()->asArray()->all(), 'course_id', 'course_name'), [
'id' => 'registrations-course_id',
'prompt' => 'Select Course',
'onchange' => '$.post("(selected:)."+$(this).val(), function(data){
$("#registrations-courses").append(data)
});'
]);
?>
<!-- <?//= $form->field($model, 'courses')->checkBoxList([]) ?> -->
<?=$form->field($model, 'courses') ?>
<?=$form->field($model, 'comment') ?>
<?=$form->field($model, 'status') ?>
<?=$form->field($model, 'created_at') ?>
<?=$form->field($model, 'updated_at') ?>
<div class="form-group">
<?=Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
EDIT
this is my controller how do I save the courses in the database in the same column?
public function actionCreate()
{
$model = new Registrations();
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
// form inputs are valid, do something here
$model->student_id = Yii::$app->user->identity->id;
$model->faculty_id = 1 ;
$model->department_id = null ;
$model->course_id = 1;
$model->save();
return $this->redirect('../site/profile');
}
}
return $this->render('create', [
'model' => $model,
]);
}
You can use the checkBoxList() to create the list of checkboxes based on the courses list.
Change your course_id field to the following
$form->field($model, 'course_id')->checkboxList(yii\helpers\ArrayHelper::map(Courses::find()->asArray()->all(), 'course_id', 'course_name'), [
'inline' => true,
'unselect'=>null,
'item' => function($index, $label, $name, $checked, $value){
$checked = $checked ? 'checked' : '';
return "<input type='checkbox' class='my-courses' name='{$name}' value='{$value}' {$checked} data-label='{$label}'> <label>{$label}</label>";
}]);
add an id attribute to your courses field like below
$form->field($model, 'courses', ['inputOptions' => ['id' => 'courses']]);
and then add this javascript code to the top of your page
$js = <<< JS
$(".my-courses").on('click',function(e){
let course_name=$(this).data('label');
let course_field=$("#courses");
if($(this).is(":checked")){
$("#courses").val()==''?course_field.val(course_name):course_field.val(course_field.val()+', '+ course_name);
}else{
let regex=new RegExp(',{0,1}\\\s{0,1}('+course_name+')','g');
course_field.val(course_field.val().replace(regex,''));
}
})
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if you select the checkbox the name of the course would be copied to the input field and when you submit your form you can get the fields in your $_POST array under your specific model index like below.
[course_id] => Array
(
[0] => 1
[1] => 2
)
[courses] => asdas, shugal, spoon
You can verify by adding a print_r(Yii::$app->request->post()) in your controller action inside the check
if($model->load(Yii::$app->request->post())){
print_r(Yii::$app->request->post());
You can iterate on the course_id to save all of the course_id that were selected as checkboxes.

Pass javascript value to a form action URL in Yii2

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]);
}

Autocomplete data fields in CakePHP

I am new in CakePHP. I have a CakePHP (2.5.1) application which has streets table (with columns id, street_name, house_no, district, city). I need to autocomplete a form by extracting the table data. It should be like, the user will be typing a street name in the Street Name field of a form which has fields- Street Name, House No, District and City. After selecting a street name from auto suggestions, corresponding data (House No, District and City) will be populated in the other fields.
Now, over 25000 data rows are loaded in the streets table which is the entire street database of a city. it is a ClearDB database on Windows Azure. streets table is not linked with other tables of the application through foreign keys. I have Street model, StreetsController , but view is in different folder (app/View/User/add.ctp ). Street model in app/Model/Street.php is following:
class Street extends AppModel {
public function getStreetNames($term = null) {
if(!empty($term)) {
$streets = $this->find('list', array(
'conditions' => array(
'street_name LIKE' => trim($term) . '%'
)
));
return $streets;
}
return false;
}
}
In app/Controller/StreetsController.php,
class StreetsController extends AppController {
public $components = array('RequestHandler');
public function autocomplete($term){
if ($this->request->is('get')) {
$this->autoRender = false;
$data = $this->Street->getStreetNames($term);
$this->set(compact('data'));
$this->set('_serialize', array('data'));
echo json_encode($data);
}
}
}
In app/webroot/js/View/Users/streetdata.js file,
(function($) {
$('#autocomplete').autocomplete({
source: "/streetdata.json",
minLength: 1
});
})(jQuery);
The input forms are in different controller. In app/View/Users/streetdata.ctp file,
<?php
echo $this->Html->script('View/Users/streetdata', array('inline' => false));
?>
<?php echo $this->Form->create('Street', array(
'class' => 'form-horizontal',
'role' => 'form',
'inputDefaults' => array(
'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
'div' => array('class' => 'form-group'),
'class' => array('form-control'),
'label' => array('class' => 'col-lg-2 control-label'),
'between' => '<div class="col-lg-3">',
'style'=>array('width:200px; height:35px;'),
'after' => '</div>',
'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
))); ?>
<fieldset>
<legend><?php echo __('Street data '); ?></legend>
<?php
echo $this->Form->input('Street.street_name', array(
'class' => 'ui-autocomplete',
'id' => 'autocomplete'));
echo $this->Form->input('Street.house_no');
echo $this->Form->input('Street.district');
echo $this->Form->input('Street.city');
?>
</fieldset>
<?php echo $this->Form->end(__('Proceed')); ?>
in View/Layouts/default.ctp, i have added followings
echo $this->Html->script('jquery.js');
echo $this->Html->script('bootstrap.min');
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('inline' => false));
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', array('inline' => false));
echo $this->Html->css('https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css');
echo $this->Html->css('font-awesome.min');
echo $this->Html->css('bootstrap.min');
echo $this->Html->meta('icon');
echo $this->fetch('meta');
echo $this->fetch('css');
echo $this->fetch('script');
echo $this->Html->charset();
But the autocomplete fields (street name and others) are not working.
I found following error messages in the console of chrome browser :
-Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:26949/Users/js/jquery.js
-Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:26949/Users/js/bootstrap.min.js
-Uncaught TypeError: Cannot read property 'offsetWidth' of undefined bootstrap.min.js:6
I am struggling to find a solution. Could anyone tell me please what is wrong here ? is it because of the location of .js file ? am i missing anything here?

Yii2 Implement client side unique validation for input field

I've one field in my big form i.e.
<?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>
Following is my ActiveForm options configuration:
<?php
$form = ActiveForm::begin([
//'id' => 'printerForm',
'enableClientValidation' => true,
'options' => [
'enctype' => 'multipart/form-data',
]
]);
?>
I want to implement client side unique validation for this. I'm using unique validator for it but its only working for server side validation.
public function rules() {
return [
[['name'], 'unique'],
]
...
other validations
...
};
Other validations working perfectly but unique client side validation is not working.
Finally I did it myself by enabling AJAX validation for a single input field and by using isAjax so that the server can handle the AJAX validation requests.
Following is the code:
In view:
<?= $form->field($model, 'name',['enableAjaxValidation' => true, 'validateOnChange' => false])->textInput(['maxlength' => 255]) ?>
And in controller:
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
$nm= $_POST['BusinessProcessProfile']['name'];
$result = Model::find()->select(['name'])->where(['name' => "$nm"])->one();
if ($result) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return \yii\widgets\ActiveForm::validate($model, 'name');
} else {
return false;
}
}
It automatically calls validations rules defined in the Model.
For more info please refer : http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation

CakePHP- Using the JsHelper for Ajax Search

Ok, So I am trying to implement sort of a livesearch using the cake's Js Helper. The user will select a criteria to search by, using a drop down, and then tyoe in his search in an input text field. So far, this is what I have.
echo $this->Form->create(false,array('type'=>'post','default'=>false));
echo $this->Form->input('criteria',array(
'label'=>'Search Criteria',
'options' => array(
'id'=> 'By ID',
'name' => 'By Name',
'blood' => 'By Blood Type',
'type' => 'By Donor Type',
'age' => 'By Age',
'gender' => 'By Gender'
)
));
?>
Here is the input:
<?php echo $this->Form->input('query', array('type' => 'text', 'id' => 'query', 'name' => 'query', 'label' => false, 'placeholder' => 'Search')); ?>
<div id="loading" style="display: none; ">
<?php echo $this->Html->image('ajax_clock.gif');?>
</div>
And this is my Js code generated using the helper!
<script type="text/javascript">
<?php
echo $this->Js->get('#query')->event('keyup',$this->Js->request(
array('controller' => 'donors', 'action' => 'search'),
array('update'=>'#results','async' => true,'dataExpression' => true,'method' => 'post','data'=>'$(\'#query,#criteria\').serializeArray()')
),false);
?>
</script>
The above Js should grab the values of the criteria drop down aswell as the value inside the input field , on the keyup event. That said, I thought it was better to encode the data, and found the serializeArray method in the doc, which should do just that (I think..)
Now, my problem is I do not know how to retrieve that serialized data from the action receiving the request. So far I have this
function search() {
if($this->request->is('post')){
$data = $this->request->input('json_decode');
}
}
So basically, I want to know how to access the data from the search action, as well as, I tried to echo the $data variable, and die($data), but I do not know where the debugging info is displayed. Any help regarding both my questions would be MUCH appreciated! thanks!

Categories