default selected in multiselect dropdown in yii - yii

it will not display default selected value in my multi select dropdown list and i am not getting the mistak. is dropdown list accept array for defalt select array list
public function actionCreate()
{
.......
$cust= implode('_',$_POST['supplier'] ['manufacture']);
$model->customer = $cust;
$model->save();
........
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->customer = explode('_',$model->customer);
if ($model->load(Yii::$app->request->post())) {
$cust= implode(',',$_POST['supplier']['manufacturer']);
$model->customer = $cust`enter code here`;
$model->save();
return $this->redirect(['view', 'id' => $model->ID]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
View
<?=
$form->field($model, 'car_manufacturer[]')->dropDownList($model->getcustinfo(), [
'multiple'=>'multiple',
'class'=>'chosen-select input-md required',
]);
?>

Pass the selected value in options:
['options' => $yourvalue => ['Selected'=>'selected']]
You should pass an array in options:
['options' =>
[
$id1 => ['selected' => true]
],
[
$id2 => ['selected' => true]
],
]
You can use foreach loop to make this array.

You should use only attribute name.
<?= $form->field($model, 'car_manufacturer')->dropDownList($model->getcustinfo(), [
'multiple'=>'multiple',
'class'=>'chosen-select input-md required', ])?>

Related

Why i getting an error "Call to a member function formName() on a non-object"

i try to save multilanguaged content
My About model
...
public function rules() {
return [
[['status', 'date_update', 'date_create'], 'integer'],
[['date_update', 'date_create'], 'required'],
];
}
...
public function getContent($lang_id = null) {
$lang_id = ($lang_id === null) ? Lang::getCurrent()->id : $lang_id;
return $this->hasOne(AboutLang::className(), ['post_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
}
My AboutLang model
public function rules()
{
return [
[['post_id', 'lang_id', 'title', 'content'], 'required'],
[['post_id', 'lang_id'], 'integer'],
[['title', 'content'], 'string'],
];
}
My About controller
public function actionCreate()
{
$model = new About();
$aboutLang = new AboutLang();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,'aboutLang'=>$aboutLang]);
}
}
and my view (create form)
...
<?= $form->field($model, 'status')->textInput() ?>
<?= $form->field($aboutLang, 'title')->textInput() ?>
<?= $form->field($aboutLang, 'content')->textInput() ?>
enter code here
And when i put $aboutLang in create form i get an error "Call to a member function formName() on a non-object"
It looks like the views you are using were generated by Gii. In that case, Gii generates a partial view for the form (_form.php) and two views both for create and update actions (create.php and update.php). These two views perform a rendering of the partial view.
The problem you might have is that you are not passing the variable $aboutLang from create.php to _form.php, that must be done in create.php, when you call renderPartial():
$this->renderPartial("_form", array(
"model" => $model,
"aboutLang" => $aboutLang, //Add this line
));
Hope it helps.
Check your $aboutLang type.
It looks like it is null.
if ($aboutLang) {
echo $form->field($aboutLang, 'title')->textInput();
echo $form->field($aboutLang, 'content')->textInput();
}

File Not uploading in yii2

I want to upload an image and save it into my database.
Here, the field name in database is image_path. When, I am trying to upload my image it shows an error: Call to a member function saveAs() on a non-object on line
$customer->file->saveAs('uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension);
If I print var_dump($customer->file); it returns NULL.
Can anyone help me to resolve this issue.
This is my view:
<?php $form = ActiveForm::begin([
'id' => 'my-profile',
'action' => \Yii::$app->urlManager->createUrl(['/myprofile', 'id_customer' => Yii::$app->user->identity->id_customer]),
'options' => ['enctype'=>'multipart/form-data']
]); ?>
<?= $form->field($customer, 'file')->fileInput() ?>
<?php ActiveForm::end(); ?>
This is my Model:
public $file;
public function rules()
{
return [
['active', 'default', 'value' => self::STATUS_ACTIVE],
['active', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
[['file'],'file'],
[['name', 'image_path'], 'string', 'max' => 200],
];
}
public function attributeLabels()
{
return [
'file' => 'Profile Picture ',
];
}
This is my controller:
public function actionMyprofile(){
$customer->file = UploadedFile::getInstance($customer,'image_path');
$customer->file->saveAs('uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension);
$customer->file = 'uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension;
}
View:
<?php $form = ActiveForm::begin([
'id' => 'my-profile',
'action' => \Yii::$app->urlManager->createUrl(['/myprofile', 'id_customer' => Yii::$app->user->identity->id_customer]),
'options' => ['enctype'=>'multipart/form-data']
]); ?>
<?= $form->field($customer, 'image_path')->fileInput() ?>
<?php ActiveForm::end(); ?>
Model:
public function rules()
{
return [
['active', 'default', 'value' => self::STATUS_ACTIVE],
['active', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
[['image_path'],'file'],
[['name', 'image_path'], 'string', 'max' => 200],
];
}
public function attributeLabels()
{
return [
'image_path' => 'Profile Picture ',
];
}
Controller:
public function actionCreate()
{
$model = new YourModel_name();
if ($model->load(Yii::$app->request->post())) {
$model->image_path = UploadedFile::getInstance($model, 'image_path');
$filename = pathinfo($model->image_path , PATHINFO_FILENAME);
$ext = pathinfo($model->image_path , PATHINFO_EXTENSION);
$newFname = $filename.'.'.$ext;
$path=Yii::getAlias('#webroot').'/image/event-picture/';
if(!empty($newFname)){
$model->image_path->saveAs($path.$newFname);
$model->image_path = $newFname;
if($model->save()){
return $this->redirect(['your redirect_path', 'id' => $model->id]);
}
}
}
return $this->render('create', [
'model' => $model,
]);
}

How to implement kartik yii2 FileInput in form Update while using different models

I have followed this solution in working with multiple models to upload using files using kartik fileinput during actionCreate.
My problem is achieving the same during actionUpdate, I keep on receiving the error below:
Either 'name', or 'model' and 'attribute' properties must be specified.
My form view is as follows:
echo $form->field($document,'document[]')->widget(FileInput::classname(), [
'options' => ['multiple' => true],
'pluginOptions' => [
// 'previewFileType' => 'any',
'showPreview' => false,
'showUpload' => false
], ]);
Whereas my controller actionUpdate is as follows
public function actionUpdate($id)
{
//$document = new EmployeeDocuments();
$model = $this->findModel($id);
$document = EmployeeDocuments::find()->indexBy('employee_id')->all();
$empavatar=$model->avatar;
$oldavatar=Yii::$app->session['oldavatar'] = $empavatar;
if ($model->load(Yii::$app->request->post()) ) {
// print_r($model); exit;
// $attachments = UploadedFile::getInstances($document, 'document');
// print_r($attachments); exit;
if($model->avatar==""){
$model->avatar=$oldavatar;
}
if ($model->save()){
if(!empty($attachments)){
foreach($attachments as $attachment):
$ext = end((explode(".", $attachment)));
$filename=end((explode(">", $attachment)));
$filename = ucwords(substr($filename, 0, strpos($filename, '.')));
// generate a unique file name
$file2save = Yii::$app->security->generateRandomString().".{$ext}";
$path=Yii::getAlias('#loc').'/uploads/employees/docs/'; //set directory path to save image
$attachment->saveAs($path.$model->id."_".$file2save); //saving img in folder
$attachment = $model->id."_".$file2save; //appending id to image name
\Yii::$app->db->createCommand()
->insert('lcm_hrm_employee_documents', ['document' => $attachment, 'name'=>$filename,'employee_id'=>$model->id])
->execute(); //manually update image name to db /* */
endforeach;
}
return $this->redirect(['view', 'id' => $model->id]);
}
else {
return $this->render('update', [
'model' => $model, 'document'=>$document
]);
}
} else {
return $this->render('update', [
'model' => $model, 'document'=>$document
]);
}
}
Change your form view to
echo $form->field($document,'document[]')->widget(FileInput::classname(), [
'options' => ['multiple' => true],
'attribute' =>'document[]',
'pluginOptions' => [
// 'previewFileType' => 'any',
'showPreview' => false,
'showUpload' => false
], ]);

`Skip on empty` not working in Yii2 file upload

I have a provision to upload logo for companies in my application. Uploading and saving on creating profile works fine. But on update, logo goes empty if I am not uploading it again!
Here's my update form
<?php $form = ActiveForm::begin([
'options' => ['enctype'=>'multipart/form-data']
]); ?>
.....
<?= $form->field($model, 'logo')->fileInput() ?>
...
My Controller action
if ($model->load($_POST) ) {
$file = \yii\web\UploadedFile::getInstance($model, 'logo');
if($file){
$model->logo=$file; }
if($model->save()){
if($file)
$file->saveAs(\Yii::$app->basePath . '/web/images/'.$file);
}
return $this->redirect(['profile']);
} else {
return $this->renderPartial('update', [
'model' => $model,
]);
}
My Rules:
public function rules()
{
return [
[['logo'], 'image', 'extensions' => 'jpg,png', 'skipOnEmpty' => true],
[['name'], 'required'],
[['name', 'description'], 'string'],
];
}
Any ideas????
skipOnEmpty does not apply here because in the update action the $model->logo attribute will not be empty, it will be a string with the file name.$file is still an array with only keys, but not values if not uploaded again. So checked the $file->size instead of checking !empty($file). Fixed the issue by modifying the controller code as follows!
$model = $this->findModel($id);
$current_image = $model->featured_image;
if ($model->load(Yii::$app->request->post())) {
$image= UploadedFile::getInstance($model, 'featured_image');
if(!empty($image) && $image->size !== 0) {
//print_R($image);die;
$image->saveAs('uploads/' . $image->baseName . '.' .$image->extension);
$model->featured_image = 'uploads/'.$image->baseName.'.'.$image->extension;
}
else
$model->featured_image = $current_image;
$model->save();
return $this->redirect(['update', 'id' => $model->module_id]);
} else {
return $this->render('add', [
'model' => $model,
]);
}
'skipOnEmpty' => !$this->isNewRecord
For update it can be skipped.

Zend - inputfilter get randomize name

Hello I'm trying ZF2 form with an input file.
I have a form with a file input and I want to insert the randomize name into my db.
How I can return the randomized name?
thanks.
This is the simple form class:
class OrdineForm extends Formhttp://stackoverflow.com/questions/ask
public function __construct($name = null)
{
parent::__construct('ordine');
$this->setAttribute('method', 'post');
$this->addElements();
$this->addInputFilter();
}
public function addElements(){
$this->add(array(
'name' => 'pdf',
'attributes' => array(
'type' => 'text',
'disabled' =>'true',
),
'options' => array(
'label' => 'PDF',
),
));
// FILE INPUT
$file = new File('file');
$file
->setLabel('PDF attach')
->setAttributes(array(
'id' => 'file',
));
$this->add($file);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Add',
'id' => 'submitbutton',
'class' => 'btn btn-success'
),
));
}
public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
$fileInput= new FileInput('file');
$fileInput->setRequired(false);
$fileInput->getFilterChain()->attachByName(
'filerenameupload',
array(
'target' => './public/tmpuploads/',
'randomize' => true,
"UseUploadname" => true,
)
);
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
}
After you have validated the form in your controller you can use $form->getData();
there should be a key 'file' as that is what you named your file element. Within that a key 'tmp_name'.
This will be the randomized name.
Eg:
public function uploadfileAction()
{
//get form and filter
$form = $this->getServiceLocator()->get('SomeModule\Form\UploadFileForm');
$filter = $this->getServiceLocator()->get('SomeModule\Form\UploadFileFilter');
$form->setInputFilter($filter->getInputFilter());
if ($this->getRequest()->isPost()) {
//merge files with post
$post = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
//set data in form
$form->setData($post);
//check is valid- form data will now contain new name
if ($form->isValid()) {
var_dump($form->getData());
}
}
}
The resulting array dump may look something like this:
array(13) {
["file"]=>
array(5) {
["name"]=>
string(14) "some-pdf.pdf"
["type"]=>
string(24) "application/pdf"
["tmp_name"]=>
string(46) "/public/tmpuploads/new-randomized-name.pdf"
["error"]=>
int(0)
["size"]=>
int(651264)
}
["submit"]=>
string(6) "Submit"
["csrf"]=>
string(32) "4df771bb2fb14e28992a408583745946"
}
You can then just do:
$formData = $form->getData();
$fileNewLocation = $formData['file']['tmp_name'];
//do what you want with $fileNewLocation