How to get last insert record - Yii 2 - yii

I am making application to create barcode
in my application, i want to create Barang but in issue slip i want issue slip filled automatically from the last issue slip
what can i do to fix it?
this is my view
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model backend\models\Barang */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="barang-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'rm_code')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'nama_barang')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'berat')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'issue_slip')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<div class="row">
<?= $form->field($model, 'berat')->textInput(['maxlength' => true]) ?>
<?php echo \Yii::$app->db->getLastInsertId('{{barang}}');?>
</div>

In controller before render
public function actionCreate()
{
$model = new Barang();
$modelForSlip = Barang::find()->orderBy(['id'=> SORT_DESC])->one();
$model->issue_slip = $modelForSlip->issue_slip;
if ($model->load(Yii::$app->request->post())){
$model->waktu = date('Y-m-d h:m:s');
$model->user = \Yii::$app->user->identity->username;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
//$model->issue_slip= \Yii::$app->db->getLastInsertId();
}
}

Let say this is your create function:
public function actionCreate()
{
$model = new Modal();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['update', 'id' => $model->Id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
then redirect to new page with last inserted ID
Now make you update function like this
public function actionUpdate($id)
{
$model2 = Model::findOne($id);
$model = new Modal();
$model->issue_slip = $model2['issue_slip'];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->Id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
In YII2 you can get last inserted record after save() function easily
like
$model->save();
echo $model->Id
or whatever column you want to get
instead of issue_slip you can use whatever column you want

Related

Yii2 How can I display Activeform radioList data on screen?

I have not experience with Yii2.
I would like to be able to show the result of a form on the screen.
With the fields name and email I have no problem but I can not show the selection
that I make of my radioList.
I have tried many methods but none works.
Can you help me please?
These are my files.
SiteController.php
public function actionEntry()
{
$this->layout = 'print';
$model = new EntryForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
return $this->render('entry-confirm', ['model' => $model]);
} else {
return $this->render('entry', ['model' => $model]);
}
}
EntryForm.php
namespace app\models;
use Yii;
class EntryForm extends \yii\db\ActiveRecord
{
public $name;
public $email;
public $category;
public function rules()
{
return [
[['name', 'email'], 'required'],
['email', 'email'],
];
}
entry.php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'category')->radioList([
1 => 'radio 1',
2 => 'radio 2'
]);
?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
entry-confirm.php
<p>You have entered the following information:</p>
<ul>
<li><label>Name</label>: <?= Html::encode($model->name) ?></li>
<li><label>Email</label>: <?= Html::encode($model->email) ?></li>
<li><label>Category</label>: <?= Html::encode($model->category) ?></li>
</ul>
This is the image with the problem:
In model extending ActiveRecord you must never explicitly define properties that are the same as names of columns in DB.
You must define at least one validation rule for each attribute that is set by the end user, otherwise system will not allow to set it.

Best way to avoid getting error in uploading a file

PHP Warning – yii\base\ErrorException
move_uploaded_file(/doc_2345.txt): failed to open stream: Permission
denied
-This is the error when i try to upload a file and save it to database(MYSQL).
I'm new with creating a website using a framework. So i don't know how to fix it.
_form.
<div class="documents-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'reference_no')->textInput() ?>
<?= $form->field($model, 'subject')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'doc_date')->textInput() ?>
<?= $form->field($model, 'doc_for')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'doc_from')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'drawer_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'doc_file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
model.
public $file;
public static function tableName()
{
return 'documents';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['reference_no', 'subject', 'doc_date', 'doc_for', 'drawer_id','doc_from', 'doc_file'], 'required'],
[['reference_no'], 'integer'],
[['doc_date'], 'safe'],
[['subject', 'doc_for', 'drawer_id','doc_from'], 'string', 'max' => 250],
[['doc_file'], 'string', 'max' => 300],
];
}
controller.
public function actionCreate()
{
$model = new Documents();
if ($model->load(Yii::$app->request->post())) {
$model->save();
$docuId = $model->reference_no;
$file = UploadedFile::getInstance($model, 'doc_file');
$docuName = 'doc_' . $docuId . '.' . $file->getExtension();
$file -> saveAs(Yii::getAlias('#webroot/filesPath') . '/' . $docuName);
$model -> doc_file = $docuName;
$model -> save();
return $this -> redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Please change folder permission and all other file & folders in which "filesPath" folder.
$file -> saveAs(Yii::getAlias('#webroot/filesPath') . '/' . $docuName);
I think it will solve your issue.

How create file input at form, which upload file and write link in database

I'm trying to learn Yii2 by writing my own cms.
I want realize attachment photo for shop items. I don't know right way to do this, but i think it's should be so -
On save, files which was selected in multiple file input are uploads to server.
Get the url by each photo
Write links in database cell by template
<div class="itemImgs">
<img class="0" src="{link}"> <!-- first -->
<img class="1" src="{link}"> <!-- second -->
<img class="..." src="{link}"> <!-- ... -->
</div>
Please, help me understand, what i must write in model and\or controller, if its right way. Else, please tell me how should to do it.
Thanks.
UPD
Action in controller:
public function actionCreate() {
$model = new ShopItems();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'category' => ShopCategories::find()->all()
]);
}
}
Model contain this functions:
public function behaviors() {
return [
TimestampBehavior::className(),
];
}
/** #inheritdoc */
public static function tableName() {return 'shop_items';}
/** #inheritdoc */
public function rules() {
return [
[['category_id', 'title', 'desc', 'price', ], 'required'],
[['category_id', 'price', 'in_stock', 'discount',], 'integer'],
[['desc', 'options',], 'string'],
[['photos',], 'file', 'maxFiles' => 10],
[['title'], 'string', 'max' => 100]
];
}
/** #inheritdoc */
public function attributeLabels() {
return [
'id' => 'ID',
'category_id' => 'Категория',
'title' => 'Название',
'desc' => 'Описание',
'price' => 'Цена',
'discount' => 'Скидка %',
'in_stock' => 'На складе',
'photos' => 'Фото',
'options' => 'Опции',
'created_at' => 'Дата добавления',
'updated_at' => 'Последнее редактирование',
];
}
And the view _form.php:
<?php $form = ActiveForm::begin(); ?>
<div class="col-lg-6">
<?= $form->field($model, 'title')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'desc')->textarea(['class' => 'ckeditor',]); ?>
</div>
<div class="col-lg-6">
<?= $form->field($model, 'category_id')->dropDownList(
ArrayHelper::map($category, 'category_id', 'category_name')
) ?>
<?= $form->field($model, 'price')->textInput() ?>
<?= $form->field($model, 'discount')->textInput() ?>
<?= $form->field($model, 'in_stock')->textInput() ?>
<?= $form->field($model, 'photos[]')->fileInput(['multiple' => true]) ?>
<?= $form->field($model, 'options')->textInput() ?>
</div>
<div class="clearfix"></div>
<div class="col-xs-12">
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Принять изменения', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
See documentation - http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html#uploading-multiple-files
In controller:
if ($model->file && $model->validate()) {
foreach ($model->file as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
}
Input model Photo:
if ($model->file && $model->validate()) {
foreach ($model->file as $file) {
$path = 'uploads/' . $file->baseName . '.' . $file->extension;
$file->saveAs($path);
$photo = new Photo();
$photo->path = $path;
$photo->save();
}
}
Photo table like that:
CREATE TABLE `photo` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`path` VARCHAR(255) NOT NULL ,
`status` TINYINT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
ENGINE=InnoDB;
Get photos use:
$photos = Photo::find()->all();
In view:
<div class="itemImgs">
<?php foreach ($photos as $k=>$photo) ?>
<img class="<?= $k ?>" src="<?= $photo->path ?>"/><br/>
<?php } ?>
</div>
EDIT
Set in controller
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$files = UploadedFile::getInstances($model, 'file');
$photosArr = [];
foreach ($files as $file) {
$path = 'uploads/' . $file->baseName . '.' . $file->extension;
$file->saveAs($path);
$photosArr[] = $path;
}
$model->photos = Json::encode($photosArr);// better put json in afterSave
$model->save(false);// because validate() run before
return $this->redirect(['view', 'id' => $model->id]);
}
In field photos you get JSON with path for uploaded photos. In view:
$arr = Json::decode($model->photos); // better put in afterFind()
foreach ($arr as $path) {
echo '<img src="'.$path.'">';
}

Yii combine yiistrap and a languages array

This is my array that prints fields for each language
<?php foreach (Yii::app()->params['translatedLanguages'] as $l => $lang) :
if($l === Yii::app()->params['defaultLanguage']) $suffix = '';
else $suffix = '_'.$l;
?>
<fieldset>
<legend><?php echo $lang; ?></legend>
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title'.$suffix,array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'title'.$suffix); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'content'); ?>
<?php echo $form->textArea($model,'content'.$suffix); ?>
<?php echo $form->error($model,'content'.$suffix); ?>
</div>
</fieldset>
<?php endforeach; ?>
This is the yiistrap code for the tabs
http://www.getyiistrap.com/site/widgets#tabs
<?php $this->widget('bootstrap.widgets.TbTabs', array(
'placement' => 'below',
'tabs' => array(
array('label' => 'Home', 'content' => 'home test', 'active' => true),
array('label' => 'Profile', 'content' => 'profile test.'),
),
)); ?>
How can I replace the content (e.g. home test) with the fields from my form?
So in the end I have a tab for each language (like opencart)
This is the code for the tabs in my view
<?php $tabs = array(); ?>
<?php foreach (Yii::app()->params['translatedLanguages'] as $l => $lang) :
if($l === Yii::app()->params['defaultLanguage']) $suffix = '';
else $suffix = '_'.$l;
?>
<?php $tabs[] = array('label' => $lang, 'view' => '_fields', 'viewData' => array('form' => $form, 'model' => $model, 'suffix' => $suffix)); ?>
<?php endforeach; ?>
<?php $this->widget('bootstrap.widgets.TbTabs', array(
'tabs' => $tabs,
'viewData' => array('form' => $form, 'model' => $model, 'suffix' => $suffix),
)); ?>
And I added another view _fields.php
<?php echo $form->textFieldControlGroup($model,'title'.$suffix,array('span'=>5,'maxlength'=>128)); ?>
<?php echo $form->textAreaControlGroup($model,'content'.$suffix,array('rows'=>6,'span'=>8)); ?>
and I changed this in TbTabs.php ($tabOptions['viewData'])
protected function normalizeTabs($tabs)
{
$controller = $this->getController();
if (isset($controller)) {
foreach ($tabs as &$tabOptions) {
$items = TbArray::getValue('items', $tabOptions, array());
if (!empty($items)) {
$tabOptions['items'] = $this->normalizeTabs($items);
} else {
if (isset($tabOptions['view'])) {
$view = TbArray::popValue('view', $tabOptions);
if ($controller->getViewFile($view) !== false) {
$tabOptions['content'] = $controller->renderPartial($view, $tabOptions['viewData'], true);
}
}
}
}
}
return $tabs;
}

Yii - How to display display captcha in CPortlet?

I'm using portlet to display contact form - the very same as is on static page which comes generated as standard. I'm using the same ContactForm model. The form displays but captcha is not displaying and reports "CCaptchaValidator.action "captcha" is invalid. Unable to find such an action in the current controller."
I'm new to yii so it takes awfully lot of time to figure everything out. Any quick advice what I shell do to make it working?
Best!
Yii::import('zii.widgets.CPortlet');
class ContactFormCard extends CPortlet
{
public $title='Contact';
protected function renderContent()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
$this->controller->refresh();
}
$this->render('contactFormCard',array('model'=>$model));
}
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
}
and in portlet view:
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
In you SiteController.php add:
public function actions() {
return array(
'captcha' => array(
'class' => 'CCaptchaAction',
'backColor' => 0xFFFFFF,
),
// [...]
);
}
In you ContactForm.php add:
public function rules() {
return array(
// [...]
array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'message' => Yii::t('formsErros', 'Código de verificação incorreto.')),
// [...]
);
}
In you view.php
<!-- [...] -->
<?php if(CCaptcha::checkRequirements()): ?>
<div class="captcha">
<?=$form->labelEx($contactFormModel, 'verifyCode')?>
<?php $this->widget('CCaptcha', array('clickableImage' => true, 'showRefreshButton' => true, 'imageOptions' => array('id' => 'captchaContactForm', 'class' => 'clickableCursor'), 'buttonLabel' => '')); ?>
<?=$form->textField($contactFormModel, 'verifyCode', array('class' => 'verticalAlignBottom'))?>
<?=$form->error($contactFormModel, 'verifyCode')?>
</div>
<?php endif; ?>
<!-- [...] -->