yii2: Undefined variable: model - yii2-advanced-app

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

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

Yii2 autocomplete no response

Am trying to display users list as mail.Here it is my code,but there is no response
<?php
$data = Users::find()
->select(['user_email as value', 'user_id as id'])
->asArray()
->all();
echo AutoComplete::widget([
'name' => 'user_email',
'id' => 'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
'select' => new JsExpression("function( event, ui ) {
$('#user_mail_1').val(ui.item.id);
}")],
]);
?>
<?= $form->field($model, 'user_email')->HiddenInput(['id' => 'user_mail_1'])->label(false) ?>
You need to use label for display value of auto complete input value.
So, get user_email as label like as:
<?php
use yii\web\JsExpression;
$data = Users::find()
->select(['user_email as value', 'user_id as id', 'user_email as label'])
->asArray()
->all();
// OR try below query for get data.
$data = (new \yii\db\Query())
->select(["user_email as value", "user_email as label","user_id as id"])
->from('users u')
->all();
echo AutoComplete::widget([
'name' => 'user_email',
'id' => 'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
'select' => new JsExpression("function( event, ui ) {
$('#".Html::getInputId($model, 'user_email')."').val(ui.item.id); // Html::gtInputId() get dynamic id of input field.
}")],
]);
?>
<?= $form->field($model, 'user_email')->hiddenInput()->label(false) ?>

Hide label for input field

I am trying to hide the label for a specific field in _form.php without success.
I have tried couple of variation like, but none is working:
<?= $form->field($model, 'sample_text')->textArea('label'=>false) ?>
and alternate code:
<?= $form->field($model, 'sample_text')->textArea('label'=>'') ?>
What is the right approach to hide a label?
Ok, I found the solution.
<?= $form->field($model, 'sample_text')->textArea()->label(false) ?>
Or you can modify template value for particular field and remove {label} part from it. I.e.:
<p><?= $form->field($page, 'image', [
'template' => '<div class=\"\">{input}</div><div class=\"\">{error}</div>'
])->fileInput() ?></p>
At time of writing after digging into the core code, I have found this to be the best solution to hide the label and prevent rendering the full field template with errors etc. for hiddenInput.
<?=
$form->field($model, 'address_uuid', [
'template' => '{input}',
'options' => ['tag' => false]
])->hiddenInput([
'readonly' => true,
])->label(false)
?>
<?= $form->field($model, 'password', [
'inputOptions'=>[
'class'=>'form-control',
'placeholder'=>'Password'
]
])->passwordInput()->label(false); ?>
<?= $sffForm->field($sffModel, 'url_keywords', ['enableLabel' => false])->textInput(['placeholder' => 'URL / keywords']) ?>
You can disable label, while creating form field class
$form->field($model, 'email', [
'inputOptions' => [
'enableLabel' => false,
]
])
The best way to hide the label in form input field, is to pass empty value to array on 'attributeLabels()' function in the model.
i.e you have input filed name 'client_name', so on the 'attributeLabels()' function's return array pass the empty string as array value
public function attributeLabels()
{
return [
'id' => 'ID',
'gender' => 'Gender',
'client_name' => '',
.
.
.
]
}

CakePHP 2.1 Contact Form in Element Won't Send

I have two contact forms in my CakePHP application -- one with its own Controller, Model, and View, and another one in an element that can be accessed as a "quick" contact form from the footer of every page on the site.
The code for both forms is the same. The element is intended to access the Controller and Model that the other form uses. However, the element is not submitting the data or sending the email, while the regular page works just fine.
Here is the MVC Code for the regular form that IS working:
<!-- Model: Model/Contact.php -->
<?php
class Contact extends AppModel {
var $name = 'Contacts';
public $useTable = false; // Not using the database, of course.
var $validate = array(
'name' => array(
'rule' => '/.+/',
'allowEmpty' => false,
'required' => true,
),
'email' => array(
'allowEmpty' => false,
'required' => true,
)
);
function schema() {
return array (
'name' => array('type' => 'string', 'length' => 60, 'class' => 'contact input'),
'email' => array('type' => 'string', 'length' => 60, 'class' => 'contact input'),
'message' => array('type' => 'text', 'length' => 2000, 'class' => 'contact input'),
);
}
}
?>
<!-- Controller: Controller/ContactsController.php -->
class ContactsController extends AppController
{
var $name = 'Contacts';
/* var $uses = 'Contact'; */
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
if(isset($this->data['Contact'])) {
$userEmail = $this->data['Contact']['email'];
$userMessage = $this->data['Contact']['message'];
$email = new CakeEmail();
$email->from(array($userEmail));
$email->to('email#example.com');
$email->subject('Website Contact Form Submission');
$email->send($userMessage);
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
public function contact() {
if(isset($this->data['Contact'])) {
$userEmail = $this->data['Contact']['email'];
$userMessage = $this->data['Contact']['message'];
$email = new CakeEmail();
$email->from(array($userEmail));
$email->to('email#example.com');
$email->subject('Website Contact Form Submission');
$email->send($userMessage);
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
// $this->redirect(array('controller' => 'pages', 'action' => 'index'));
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
}
?>
<!-- View: Views/Contacts/index.ctp -->
<?
$main = 'contact';
$title = 'quick contact';
?>
<div style="border-bottom: solid 1px #ccc;">
<h1 style="position:relative; float:left;"><?php echo $main; ?></h1>
<h2 style="position:relative;float:left;margin-top:15px; color: #869c38"> • <?php echo $title;?></h2>
<br><br>
</div>
<div class="clear"><br></div>
<div id="interior-page">
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('name', array('default' => 'name (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('email', array('default' => 'email (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('message', array('default' => 'message', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->submit();
echo $this->Form->end();
?>
</div>
And here is the view for the quick contact form that is NOT working, located in an element displayed in the footer of the default layout:
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('name', array('default' => 'name (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('email', array('default' => 'email (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('message', array('default' => 'message', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->submit();
echo $this->Form->end();
?>
I tried different ways of changing the form action, but I couldn't figure that out.
Usually, cake "automagically" creates the action of the form based on where you call it from E.g. if called from the view Views/Contacts/index.ctp, it will set the action to /contacts/index. In case of an element, Cake can't really guess what you're trying to do, so you need to set the action manually:
$this->Form->create('Contact', array('action' => 'index'));
Or set the full URL alternatively:
$this->Form->create('Contact', array('url' => '/contacts/index'));
Make sure you're including the Contact model for use on every page you need to create that form. In your case, since it's in your layout, that likely means you should put it in your AppController, so every page has access to it.
You also need to specify where the form should submit to:
echo $this->Form->create('Contact', array(
'url' => array('controller'=>'contacts', 'action'=>'contact')
)
);
Off-note - You can combine the last 2 lines:
echo $this->Form->end('Submit');
This creates the submit button with text "Submit" and also closes the form.
Thanks for this! It helped me a lot.
Just a quick thing, you're sending the email twice.
Once here:
$email->send($userMessage);
And again here:
if ($email->send($userMessage))
The first instance ($email->send($userMessage)) isn't necessary.
Cheers