I am using YII2 advanced and I am trying from some hour but not any code working for me. I want to create dropdown from user table in my post page. I have found this error Class 'yii\models\user' not found. i have created this post with GII. my _form.php code
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\models\user;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Posts */
/* #var $form yii\widgets\ActiveForm
<?php/* <?= $form->field($model, 'id')->textInput(['value' => \Yii::$app->user->identity->id]) ?>
use yii\models\user;
*/
?>
<div class="posts-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'post_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'post_description')->textarea(['rows' => 6]) ?>
<?php
echo Html::activeDropDownList($model, 'author_id',ArrayHelper::map(User::find()->all(),'id','username'),['prompt'=>'Select User']);
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Why not working please anyone help me.
Thanks in advence
User::find() shows that you would use a User model, so really in uppercase as scaisEdge has answered to you.
However you have to know, in what namespace your User model is sitting. Yii2 doesn't have a User model, you have to create it. You mentioned, that you are using the advanced template. In that case you should create a User model in 'common/models/User.php' instead of 'models/User.php'. Follow the description in the Yii2 Guide.
In php typically a class name begin with an Uppercase char so in a unix like env (with file system based on a case sensitive constrain ) this must match try
use yii\models\User;
Related
I tried to make a dropdown list in yii2 using this link : How to make a drop down list in yii2?
my code is :
<?php use yii\helpers\ArrayHelper;
use app\models\Product;
?>
<?= $listdata=ArrayHelper::map(Product::find()->all(),'id','name'); ?>
<?= $form->field($model, 'parent_id')-> dropDownList($listdata); ?>
but I have a problem in line of using ArrayHelper
the problem is:
PHP Notice – yii\base\ErrorException
Array to string conversion.......! I tested the below code :
$listData=ArrayHelper::map(Product::find()->asArray()->all(),'id','name');
but it dos not solved and has the same error!
whats the problem? can somebody help me?
You are trying to echo an array, change <?= to <?php in:
<?= $listdata=ArrayHelper::map(Product::find()->all(),'id','name'); ?>
Try like this
<?php
use yii\helpers\ArrayHelper;
use app\models\Product;
?>
<?= $form->field($model, 'parent_id')->dropDownList(
ArrayHelper::map(Product::find()->all(),'id','name'),
['prompt'=>'Select '])
?>
I want to create dropdownbox in Yii framework which have name is Category,I copy in the stackoverflow but it has error,
<form>
<?php
$list = CHtml::listData(Categories::model()->findAll(array('order' => 'cate_name')), 'id', 'cate_name');
echo $form->dropDownList("Category", 'cate_name', $list);
?>
</form>
here is error:
Undefined variable: form
Your form should looks like this:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'your-form',
'enableAjaxValidation'=>false,
)); ?>
<?php
$list = CHtml::listData(Categories::model()->findAll(array('order' => 'cate_name')), 'id', 'cate_name');
echo $form->dropDownList("Category", 'cate_name', $list);
?>
<?php $this->endWidget(); ?>
NOTE: replace form tag with form widget
Instead of using html form tag, you have to use yii form widget.
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'form_id',
)); ?>
For tutorial: http://www.yiiframework.com/doc/guide/1.1/en/form.view
hopefully a quick question here, have not been able to find out the answer on google. Anyway I have the following File upload field.
<div class="row">
<?php echo CHtml::form('', 'post', array('enctype' => 'multipart/form-data')); ?>
<?php echo $form->labelEx($model, 'doc'); ?>
<?php echo CHtml::activeFileField($model, 'doc'); ?>
<?php echo $form->error($model, 'doc'); ?>
</div>
The question I have is how to change the default text? On the page in question the upload field comes up with "No file chosen" beside the button when the page loads. I wish to change this text, anyone tell me how? Thanks.
I quick & dirty fix is this:
<?php echo CHtml::activeFileField($model, 'type',array('style'=>'width:100px;', 'onchange' => 'this.style.width = "100%";')); ?>
I'm a new to yii, so I was following this tutorial.
when I try to upload picture it reports empty field even if it is not.
my _form view:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'picture-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
...
<div class="row">
<?php echo $form->labelEx($model,'path_to'); ?>
<?php echo $form->fileField($model,'path_to'); ?>
<?php echo $form->error($model,'path_to'); ?>
</div>
...
<?php $this->endWidget(); ?>
</div><!-- form -->
and here is my action method:
public function actionCreate()
{
$model=new Picture;
if(isset($_POST['Picture']))
{
$model->attributes=$_POST['Picture'];
$model->picture=CUploadedFile::getInstance($model,'path_to');
if($model->save()){
$log->lwrite('in save'.$model->picture);
$model->picture->saveAs(Yii::app()->basePath.'/../images/'.$model->picture);
$this->redirect(array('view','id'=>$model->id));
$log->lclose();
}
}
$this->render('create',array('model'=>$model,));
}
when I print_r($_FILES) everything what should be there is there
when I print_r($_POST) the field 'path_to' is empty and the validator probably is picking that one.
I'm probably missing something here and I'm clueless.
update1:
I've noticed yii is using hidden field with the same name as file input, than attributes are read from $_POST, which is causing the engine reading empty hidden field.
I understand that the hidden field is there for update when user is not entering new picture.
Can anyone advice what is the best way of doing picture upload?
update2:
model code:
class Picture extends CActiveRecord
{
public $picture;
...
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('path_to, page_id', 'required'),
array('page_id', 'numerical', 'integerOnly'=>true),
array('alt_text', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, alt_text, path_to, page_id', 'safe', 'on'=>'search'),
//array('path_to', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
//array('path_to', 'length', 'max'=>255, 'on'=>'insert,update'),
array('path_to', 'unsafe'),
);
}
...
Best!
I think because you've declared 'path_to' to be unsafe in your rules, the massive assignment line:
$model->attributes=$_POST['Picture'];
Will fail, which will then cause the rule validation to fail. Change your rules to allow for path_to to be safe, and you should be good to go . . .
It also appears you're requiring a page_id, which I'm not seeing in your form.
_form code for file upload field :
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'post-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<div class="row">
<?php echo $form->labelEx($model, 'image');?>
<?php echo $form->fileField($model, 'image'); ?>
<?php echo $form->error($model, 'image'); ?>
</div>
<?php $this->endWidget(); ?>
Controller Code:
public function actionCreate()
{
$model=new Post;
if(isset($_POST['Post']))
{
$model->attributes=$_POST['Post'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = $uploadedFile;
$model->image = $fileName;
if($model->save()){
$uploadedFile->saveAs('C:/Program Files/Apache Group/Apache2/htdocs'.Yii::app()->baseUrl.'/images/thumbnails/'.$fileName);
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
diplay view code :
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'ajaxUpdate' => false,
'columns'=>array(
array(
'name'=>'Thumbnail',
'value'=>array($model,'showThumbnail'), // function in model
'type'=>'html',
'htmlOptions'=>array('class'=>'thumbnail'),
),
)
));
?>
model code :
place this function in ur model :
public function showThumbnail($data){
$path = $data->image;
return CHtml::image(Yii::app()->baseUrl.'/images/thumbnails/'.$path); // same path as ur uploaded file path
}
Now I am building the view of a website and I use the widget CActiveForm as the view. However, I need to display some of the contents of the database, for example, the result of a SQL query. Then what should I do to accomplish the goal? Thank you!
Some of my code is provided below:
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row buttons">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<div class="row radiobuttons">
<?php echo CHtml::radioButtonList(
$Paper,
'Q1No',
array('A'=>'A','B'=>'B','C'=>'C','D'=>'D'),
array('template'=>'<span class="radio">{input}{label}</span>','separator'=>''));
?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
This is my code. And I need to add some contents of the database in the form. The content is listed below:
public function actionTaketest()
{
// Get the ID of the test paper from the URL ---ztm
if(isset($_GET['paperid']))
{
$paperid=(int)$_GET['paperid'];
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'root';
$password = '000000';
$connection=new CDbConnection($dsn,$username,$password);
// establish connection. You may try...catch possible exceptions
$connection->active=true;
$rawData = Yii::app()->db->createCommand()
->select('*')
->from('Paper, Question') array(':PaperNo'=>$paperid))
->queryAll();
$dataProvider=new CArrayDataProvider($rawData, array(
'id'=>'PaperNo',
));
$connection->active=false; // close connection
$model=new LoginForm;
$this->render('form',array('model'=>$model, 'dataProvider'=>$dataProvider));
}
else
{
// Deny illegal access to the page ---ztm
throw new CHttpException(404,'invalid request');
}
}
This code are in the controller.
Your code is too messy, and looks invalid in some places. First of all you don't need to create CDbConnection in controller, you can specify credentials in config. To read data from database you can use ActiveRecord:
$paper = Paper::model()->findByAttributes(array('PaperNo' => $paperid));
And then in your html:
echo CHtml::activeRadioButtonList(
$paper,
'Q1No',
array('A'=>'A','B'=>'B','C'=>'C','D'=>'D'),
array('template'=>'<span class="radio">{input}{label}</span>','separator'=>'')
);
I hope it helps a little bit.