How to set id for AJAX - yii2-advanced-app

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'
]) ?>

Related

Invalid argument supplied for foreach() in \zendframework\zend-form\src\Form.php on line 773 when using $form->prepare() Zend Framework 3

I'm newbie ZF3
I had finished my searching form and implementing the autocomplete suggestion using zend framework 3 but I got an error message warning : in Invalid argument supplied for foreach() in \zendframework\zend-form\src\Form.php on line 773
Then I do remove $form->prepare(); and message error doesn't appear but once the button is clicked and verified then the error message back
my addkelas.phtml
<?php
$form->setAttribute('action',$this->url('kelasbimbingan',['action'=>'addkelas']));
$form->prepare();
echo $this->form()->openTag($form);
?>
<p>Type students names:</p>
<div id="prefetch">
<?= $this->formElement($form->get('nama')); ?>
</div>
<br>
<div>
<?php
echo $this->formSubmit($form->get('submit'))."<br>";
echo $this->form()->closeTag();
?>
</div>
<?php
echo "<script language='javascript'> var country_list =".$data.";</script>";
$this->headScript()
->appendFile('/js/typeahead.bundle.js', 'text/javascript')
->appendFile('/js/bloodhound.js', 'text/javascript')
->appendFile('/js/autocompletejavascript.js', 'text/javascript');
?>
my addkelasAction()
public function addkelasAction()
{
$form = new CarimahasiswaForm();
$data = \Zend\Json\Json::encode($this->getMahasiswaData());
if ($this->getRequest()->isPost()) {
//get data, fill in the form with POST data
// Fill in the form with POST data
$dataMahasiswa = $this->params()->fromPost();
$form->setData($dataMahasiswa);
//validate form
// print_r($data);
if($form->isValid()){
$dataMahasiswa = $form->getData();
print_r($dataMahasiswa);
}
}
return new ViewModel(['form'=>$form,'data'=>$data]);
}
and my form
<?php
namespace Skripsiku\Form;
use Zend\Form\Form;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilter;
use Zend\Form\Element;
class CarimahasiswaForm extends Form
{
public function __construct()
{
parent::__construct('tambah-kelas');
$this->getElements();
$this->add([
'name'=>'submit',
'type'=>'submit',
'attributes'=>[
'value'=>'Cari Mahasiswa',
'id'=>'SaveButton',
'class'=>'btn btn-info btn-md',
],
]);
}
public function getElements()
{
$this->add([
'name'=>'nama',
'type'=>'text',
'attributes'=>[
'placeholder'=>'Ketik Nama Mahasiswa',
'class'=>'typeahead',
],
'options'=>[
'label'=>'Cari Mahasiswa :',
]
]);
}
private function addInputFilter()
{
// Create main input filter
$inputFilter = new InputFilter();
$this->setInputFilter($inputFilter);
$inputFilter->add([
'name' => 'nama',
'required' => true,
'filters' => [
['name' => 'StringTrim'],
['name' => 'StripTags'],
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 5,
'max' => 255,
],
],
],
]);
}
}
?>
please suggest..
Sorry for my bad English.. Thanks
Zend Form extends Fieldset which declares a getElements function
public function getElements()
{
return $this->elements;
}
The line which throws the exception/error tries to loop through a value retrieved from:
$elements = $fieldset->getElements();
You might think that $fieldset != $this in the given context, but zend handles forms like fieldset:
$this->attachInputFilterDefaults($this->filter, $this);
Solution: Don't overwrite the getElements function, either rename your current function or add that piece of code to your constructor.

Yii2 form input field counts with value from db

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).

yii2: Undefined variable: model

I am just starting Yii2 framework.
I want to create a dropdown list which is 1 to 10 and a submit button
Once select the option and click the button should go to next page to show the number I choose.
In my view file : index.php
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'QTY')->dropDownList(range(1, 10)) ?>
<?= Html::submitButton('Buy', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
Then when I go to the page it gave me 'Undefined variable: model' at dropdown list there.
What should I do to make it correct?
And what is the different between Html and CHtml?
Thanks.
this code is form.php not index.php.
because we can see, there are active form.
your model is undefined maybe you write the wrong code
this is example of controller index.php
public function actionIndex()
{
$searchModel = new PersediaanBarangSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Html and Chtml is the same
in Yii1=CHtml
in Yii2=Html
This is ment to be pagination? If yes use default functionality of the grid view.
This goes to controller:
$query = Post::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC,
'title' => SORT_ASC,
]
],
]);
return $this->render('path_to_view',['dataProvider'=>$provider]);
Read more
This goes to view:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
'created_at:datetime',
// ...
],
]);
Read more
Actually you model is not loaded, Please check below example.
public function actionIndex($id = Null)
{
$data=array();
$data['model'] = !empty($id) ? \app\models\YourModel::findOne($id) : new \app\models\YourModel();
return $this->render('index', $data);
}

Yii2 Modal Dialog on Gridview update button not load the update form

With reference to How to implement Yii2 Modal Dialog on Gridview view and update button?. I did my code below, but it popups a window with no update form. could anyone please let me know the correct code? (i use Kartik Gridview)
This is the code for column:
['class' => '\kartik\grid\ActionColumn',
'template'=>'{update}{delete}{view}',//{view}'//{view}{delete}',
'headerOptions' => ['width' => '20%', 'class' => 'activity- update-link',],
'contentOptions' => ['class' => 'padding-left-5px'],
'buttons' => [
'update' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>','/projects/update?id='.$key.'', [
'class' => 'activity-update-link',
'title' => Yii::t('yii', 'Project Update'),
'data-toggle' => 'modal',
'data-target' => '#activity-modal',
'data-id' => $key,
'data-pjax' => '0',
]);
},
],
],
This is JS code:
<?php $this->registerJs(
'
function init_click_handlers(){
$(".activity-update-link").click(function(e) {
var fID = $(this).closest("tr").data("key");
$.get(
"update",
{
id: fID
},
function (data)
{
$("#activity-modal").find(".modal-body").html(data);
$(".modal-body").html(data);
$("#activity-modal").modal("show");
}
);
});
}
init_click_handlers(); //first run
$("#project_pjax_id").on("pjax:success", function() {
init_click_handlers(); //reactivate links in grid after pjax update
});
');
?>
<?php
Modal::begin([
'id' => 'activity-modal',
'header' => '<h4 class="modal-title">Update Project Testing</h4>',
'size'=>'modal-lg',
'footer' => '<a href="#" class="btn btn-primary" data-
dismiss="modal">Close</a>',
]); ?>
<div class='well'></div>
<?php Modal::end(); ?>
Thanks all for watching my question. I solved my issue by adding modal into main.js file of the assets folder using class instead of ID.

Yii CJuiAutoComplete default display value and clearing it on click

I have below CJuiAutoComplete and when loading I want to display "Search" in the text field and on click I want to clear . I tried using "value" under options , but couldn't make it work . Thanks for your help
tried also
'htmlOptions'=>array('value'=>'Search',)
<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'test1',
'source'=>'js: function(request, response) {
$.ajax({
url: "'.$this->createUrl('myAutoComplete/autoCompleate').'",
dataType: "json",
data: {
term: request.term,
brand: $("#type").val()
},
success: function (data) {
response(data);
}
})
}',
'options' => array(
'showAnim' => 'fold',
'select' => 'js:function(event, ui){ alert(ui.item.value) }',
'click'=>'js:function( event, ui ) {
alert("test");
return false;
}',
),
'htmlOptions'=>array('value'=>'Search',)
));
?>
Regards
UPDATE
directly putting 'value' =>'Search' worked .
Checking for click handler
Kiran
What you can do is give your widget an id and then you place the onClick event in the widget's htmlOptions and using JavaScript you clear the value.
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'id' => 'test1_id',
'name'=> 'test1',
'source'=>'js: function(request, response) {
$.ajax({
url: "'.$this->createUrl('myAutoComplete/autoCompleate').'",
dataType: "json",
data: {
term: request.term,
brand: $("#type").val()
},
success: function (data) {
response(data);
}
})
}',
'options' => array(
'showAnim' => 'fold',
'select' => 'js:function(event, ui){ alert(ui.item.value) }',
),
'htmlOptions' => array(
'onClick' => 'document.getElementById("test1_id").value=""'
)
));
You cannot put onClick in the options attribute as these are jQuery options for the CJuiAutocomplete, onClick is not defined in the JUI Autocomplete options.
Cheers
Old thread, but for newbies who land up here, its simple to add a html placeholder attribute in Yii CAutoComplete. See code below and add in the htmloptions line:
<?php $this->widget('CAutoComplete', array(
'model'=>$model,
'attribute'=>'tags',
'url'=>array('suggestTags'),
'multiple'=>true,
'htmlOptions'=>array('size'=>50,'placeholder'=>'Seperate tags with commas'),
)); ?>