Activeform data submit in database using Yii2, Not working - yii2

I m new in yii2 framework, when I submit my Activeform data to save in database in display error
Not Found (#404).
This Activeform mention in different model view. My form is on product page and I want just give review of customer regarding this product and save in DB.
view file: detail.php:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Product */
$name = $result->name;
$price = $result->price;
$offerrate = 8;
$offer = ($price / 100) * $offerrate;
$offerprice = number_format($price - $offer, 2);
$text = $result->Description;
$list = explode(",", $text);
?>
<div id="page-content" class="home-page">
<div class="container">
<div class="row">
<div class="col-lg-5">
<center>
<?= Html::img(Yii::$app->urlManagerBackend->BaseUrl.'/'.$result->image, ['alt'=>'myImage','width'=>'300','height'=>'300', 'class' => 'img-responsive']) ?>
<br/>
<?= Html::button('ADD TO CART', ['class' => 'btn btn-success', 'id'=>'addcart']) ?>
<?= Html::button('BUY NOW', ['class' => 'btn btn-danger', 'id'=>'buynow']) ?>
</center>
</div>
<div class="col-lg-7">
<?php echo "<h5 style='color:#009933'>".$name."</h5>"?><br/>
<?php
echo "<ul>";
foreach ($list as $lists)
{
echo "<li class='liststyle'>".$lists."</li>";
}
echo "</ul>";
?><br/>
<?php echo "<h6 style='color:#009933'>MobileShop Offer Price Rs: ".$offerprice."</h6>" ?>
<?= Html::button('Rate and Review product', ['class' => 'btn btn-default', 'id'=>'review', 'data-toggle' => 'collapse', 'data-target' => '#demo']) ?>
<div id="demo" class="collapse">
<?php $form = ActiveForm::begin(['id' => 'reviewForm', 'action' => Yii::$app->urlManager->createUrl(['TblFeedback/create'])]); ?>
<?= $form->field($feedback, 'cust_name')->textInput() ?>
<?= $form->field($feedback, 'feedback')->textArea(['rows' => '2', 'cols' => '10'])?>
<?= $form->field($feedback, 'rating')->dropDownlist(['1' => '*', '2' => '* *', '3' => '* * *', '4' => '* * * *', '5' => '* * * * *']) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['id' => 'savebtn', 'class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
</div>
Controller file: TblFeedbackController.php
<?php
namespace frontend\controllers;
use Yii;
use app\models\TblFeedback;
use frontend\models\Product;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
class TblFeedbackController extends \yii\web\Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionCreate()
{
$feedback = new TblFeedback();
if ($feedback->load(Yii::$app->request->post()) && $feedback->validate())
{
var_dump($feedback);
die();
$feedback->save();
Yii::$app->session->setFlash('success', '<h5>Thanks for review!</h5>');
return $this->redirect(['index']);
}
else {
return $this->render('index',
['feedback' => $feedback,
]);
Yii::$app->session->setFlash('error', 'Error Found!');
}
}
}
model file: TblFeedback.php
<?php
namespace frontend\models;
use Yii;
/**
* This is the model class for table "tbl_feedback".
*
* #property integer $id
* #property integer $product_id
* #property integer $cust_id
* #property string $cust_name
* #property integer $rating
* #property string $feedback
*
* #property Product $product
* #property User $cust
*/
class TblFeedback extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'tbl_feedback';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['product_id', 'cust_id', 'cust_name', 'rating', 'feedback'], 'required'],
[['product_id', 'cust_id', 'rating'], 'integer'],
[['rating'], 'integer', 'min' => 1, 'max' => 5],
[['cust_name'], 'string', 'max' => 200],
[['feedback'], 'string', 'max' => 1000],
[['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
[['cust_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['cust_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'product_id' => 'Product ID',
'cust_id' => 'Cust ID',
'cust_name' => 'Enter Name:',
'rating' => 'Rating',
'feedback' => 'Description',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProduct()
{
return $this->hasOne(Product::className(), ['id' => 'product_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCust()
{
return $this->hasOne(User::className(), ['id' => 'cust_id']);
}
}

The naming convention for controller action are based on - separator when a part is uppercase so you should use
<?php $form = ActiveForm::begin(['id' => 'reviewForm',
'action' => Yii::$app->urlManager->createUrl(['Tbl-feedback/create'])]); ?>
the naming convention,for the controllers, it is to start with a lowercase character.
so you should use
class tblFeedbackController extends \yii\web\Controller
and
<?php $form = ActiveForm::begin(['id' => 'reviewForm',
'action' => Yii::$app->urlManager->createUrl(['tbl-feedback/create'])]); ?>
and last suggestion you could use urlHelper
use yii\helpers\Url;
<?php $form = ActiveForm::begin(['id' => 'reviewForm',
'action' => Url::to(['tbl-feedback/create'])]); ?>

Related

Can't delete selected image when update the form by using Yii kartik fileinput

I refer to this link https://github.com/jaradsee/faktharm/blob/master/controllers/PhotoLibraryController.php
to upload multiple images but when I try to delete the selected image in update form it showing me these error
(image1)
(image2)
For image 2, why the url link always give products%252Fdeletefile-ajax (give number 25)
Below is my code, please help me to check what's goes wrong, thank you!
Uploads.php
class Uploads extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'uploads';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['file_name'], 'required'],
[['upload_id'], 'integer'],
[['create_date'], 'safe'],
[['ref'], 'string', 'max' => 100],
[['file_name', 'real_filename'], 'string', 'max' => 150],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'upload_id' => 'Upload ID',
'ref' => 'Ref',
'file_name' => 'File Name',
'real_filename' => 'Real Filename',
'create_date' => 'Create Date',
];
}
}
Products.php
class Products extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
//public $file;
const UPLOAD_FOLDER='products';
public static function tableName()
{
return 'products';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['productName', 'productDescription', 'productPrice', 'categoryId', 'brandId', 'productStatus'], 'required'],
[['productDescription', 'productStatus'], 'string'],
[['productPrice'], 'number'],
[['categoryId', 'brandId'], 'integer'],
[['productName','ref'], 'string', 'max' => 100],
[['brandId'], 'exist', 'skipOnError' => true, 'targetClass' => Brands::className(), 'targetAttribute' => ['brandId' => 'brandId']],
[['categoryId'], 'exist', 'skipOnError' => true, 'targetClass' => Categorys::className(), 'targetAttribute' => ['categoryId' => 'categoryId']],
[['ref'],'unique']
// ['productImage', 'file','maxFiles'=>5],
//[['file'],'productImage']
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'productId' => 'Product ID',
'productName' => 'Product Name',
'productDescription' => 'Product Description',
'productPrice' => 'Product Price',
'ref' => 'Product Image',
'categoryId' => 'Category',
'brandId' => 'Brand',
'productStatus' => 'Product Status',
];
}
/**
* Gets query for [[Brand]].
*
* #return \yii\db\ActiveQuery
*/
public function getBrand()
{
return $this->hasOne(Brands::className(), ['brandId' => 'brandId']);
}
/**
* Gets query for [[Category]].
*
* #return \yii\db\ActiveQuery
*/
public function getCategory()
{
return $this->hasOne(Categorys::className(), ['categoryId' => 'categoryId']);
}
public function getImages()
{
return $this->hasMany(Images::className(), ['productId' => 'productId']);
}
public static function getUploadPath(){
return Yii::getAlias('#webroot').'/'.self::UPLOAD_FOLDER.'/';
}
public static function getUploadUrl(){
return Url::base(true).'/'.self::UPLOAD_FOLDER.'/';
}
public function getThumbnails($ref,$event_name){
$uploadFiles = Uploads::find()->where(['ref'=>$ref])->all();
$preview = [];
foreach ($uploadFiles as $file) {
$preview[] = [
'url'=>self::getUploadUrl(true).$ref.'/'.$file->real_filename,
'src'=>self::getUploadUrl(true).$ref.'/thumbnail/'.$file->real_filename,
'options' => ['title' => $event_name]
];
}
return $preview;
}
}
ProductsController.php
namespace backend\controllers;
use Yii;
use backend\models\Products;
use backend\models\Uploads;
use backend\models\ProductsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Json;
use yii\widgets\ActiveForm;
use yii\web\UploadedFile;
use yii\helpers\Url;
use yii\helpers\html;
use yii\helpers\BaseFileHelper;
use yii\helpers\ArrayHelper;
/**
* ProductsController implements the CRUD actions for Products model.
*/
class ProductsController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
// 'access' => [
// 'class' => AccessControl::className(),
// 'rules' => [
// [
// 'actions' => ['view','update','_form','index','_search','create','uploadAjax','createDir'],
// 'allow' => true,
// 'roles' => ['admin'],
// ],
// ],
// ],
];
}
/**
* Lists all Products models.
* #return mixed
*/
public function actionIndex($pageSize = 10)
{
$searchModel = new ProductsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $pageSize);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'pageSize' => $pageSize,
]);
}
/**
* Displays a single Products model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Products model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
/*public function actionCreate()
{
$model = new Products();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->imageFiles = UploadedFile::getInstances($model, 'productImage');
return $this->redirect(['view', 'id' => $model->productId]);
}
return $this->render('create', [
'model' => $model,
]);
}*/
public function actionCreate()
{
$model = new Products();
if ($model->load(Yii::$app->request->post())) {
$this->Uploads(false);
if($model->save()){
return $this->redirect(['view', 'id' => $model->productId]);
}
}
else{
$model->ref = substr(Yii::$app->getSecurity()->generateRandomString(),10);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Products model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
list($initialPreview,$initialPreviewConfig) = $this->getInitialPreview($model->ref);
if ($model->load(Yii::$app->request->post())) {
$this->Uploads(false);
if($model->save()){
return $this->redirect(['view', 'id' => $model->productId]);
}
}
return $this->render('update', [
'model' => $model,
'initialPreview'=>$initialPreview,
'initialPreviewConfig'=>$initialPreviewConfig
]);
}
/**
* Deletes an existing Products model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
//$model = new Products();
//$this->findModel($id)->delete();
$model->$this->findModel($id);
$this->removeUploadDir($model->ref);
Uploads::deleteAll(['ref'=>$model->ref]);
$model->delete();
return $this->redirect(['index']);
}
/**
* Finds the Products model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Products the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Products::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/*|*********************************************************************************|
|================================ Upload Ajax ====================================|
|*********************************************************************************|*/
public function actionUploadAjax(){
$this->Uploads(true);
}
private function CreateDir($folderName){
if($folderName != NULL){
$basePath = Products::getUploadPath();
if(BaseFileHelper::createDirectory($basePath.$folderName,0777)){
BaseFileHelper::createDirectory($basePath.$folderName.'/thumbnail',0777);
}
}
return;
}
private function removeUploadDir($dir){
BaseFileHelper::removeDirectory(Products::getUploadPath().$dir);
}
private function Uploads($isAjax=false) {
if (Yii::$app->request->isPost) {
$images = UploadedFile::getInstancesByName('upload_ajax');
if ($images) {
if($isAjax===true){
$ref =Yii::$app->request->post('ref');
}else{
$Products = Yii::$app->request->post('Products');
$ref = $Products['ref'];
}
$this->CreateDir($ref);
foreach ($images as $file){
$fileName = $file->baseName . '.' . $file->extension;
$realFileName = md5($file->baseName.time()) . '.' . $file->extension;
$savePath = Products::UPLOAD_FOLDER.'/'.$ref.'/'. $realFileName;
if($file->saveAs($savePath)){
if($this->isImage(Url::base(true).'/'.$savePath)){
$this->createThumbnail($ref,$realFileName);
}
$model = new Uploads;
$model->ref = $ref;
$model->file_name = $fileName;
$model->real_filename = $realFileName;
$model->save();
if($isAjax===true){
echo json_encode(['success' => 'true']);
}
}else{
if($isAjax===true){
echo json_encode(['success'=>'false','eror'=>$file->error]);
}
}
}
}
}
}
private function getInitialPreview($ref) {
$datas = Uploads::find()->where(['ref'=>$ref])->all();
$initialPreview = [];
$initialPreviewConfig = [];
foreach ($datas as $key => $value) {
array_push($initialPreview, $this->getTemplatePreview($value));
array_push($initialPreviewConfig, [
'caption'=> $value->file_name,
'width' => '120px',
'url' => Url::to(['/products/deletefile-ajax']),
'key' => $value->upload_id
]);
}
return [$initialPreview,$initialPreviewConfig];
}
public function isImage($filePath){
return #is_array(getimagesize($filePath)) ? true : false;
}
private function getTemplatePreview(Uploads $model){
$filePath = Products::getUploadUrl().$model->ref.'/thumbnail/'.$model->real_filename;
$isImage = $this->isImage($filePath);
if($isImage){
$file = Html::img($filePath,['class'=>'file-preview-image', 'alt'=>$model->file_name, 'title'=>$model->file_name]);
}else{
$file = "<div class='file-preview-other'> " .
"<h2><i class='glyphicon glyphicon-file'></i></h2>" .
"</div>";
}
return $file;
}
private function createThumbnail($folderName,$fileName,$width=250){
$uploadPath = Products::getUploadPath().'/'.$folderName.'/';
$file = $uploadPath.$fileName;
$image = Yii::$app->image->load($file);
$image->resize($width);
$image->save($uploadPath.'thumbnail/'.$fileName);
return;
}
public function actionDeletefileAjax(){
$model = Uploads::findOne(Yii::$app->request->post('key'));
if($model!==NULL){
$filename = Products::getUploadPath().$model->ref.'/'.$model->real_filename;
$thumbnail = Products::getUploadPath().$model->ref.'/thumbnail/'.$model->real_filename;
if($model->delete()){
#unlink($filename);
#unlink($thumbnail);
echo json_encode(['success'=>true]);
}else{
echo json_encode(['success'=>false]);
}
}else{
echo json_encode(['success'=>false]);
}
}
}
_form.php
<?php
//use kartik\file\FileInput;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use backend\models\Brands;
use backend\models\Categorys;
use yii\helpers\Url;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model backend\models\Products */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="photo-library-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?php $form->errorSummary($model) ?>
<?= $form->field($model, 'ref')->hiddenInput(['maxlength' => 100])->label(false); ?>
<?= $form->field($model, 'productName')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'productDescription')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'productPrice')->textInput() ?>
<?=
$form->field($model, 'brandId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Brands::find()->where(['brandStatus'=>'active'])->all(),'brandId','brandName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a brand ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?=
$form->field($model, 'categoryId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Categorys::find()->where(['categoryStatus'=>'active'])->all(),'categoryId','categoryName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a category ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'productStatus')->dropDownList([ 'active' => 'Active', 'inactive' => 'Inactive', ], ['prompt' => 'Status']) ?>
<div class="form-group field-upload_files">
<label class="control-label" for="upload_files[]"> Product Images </label>
<div>
<?=
FileInput::widget([
'name' => 'upload_ajax[]',
//'attribute'=>'productImage[]',
//'name'=>'productImage[]',
'options' => [
'multiple'=>true,
'accept' => 'image/*',
//'id'=>'imageId',
],
'pluginOptions' => [
'initialPreview'=> $initialPreview,
'initialPreviewConfig'=> $initialPreviewConfig,
'deleteUrl'=>Url::to(['/products/deletefile-ajax']),
'showPreview' => true,
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'uploadAsync' => true,
'uploadUrl'=>Url::to(['/products/upload-ajax']),
'maxFileCount' => 5,
'allowedFileExtensions' => ['jpg', 'png','jpeg'],
'previewFileType' => ['jpg', 'png','jpeg'],
'overwriteInitial'=>false,
'uploadExtraData' => [
'ref'=>$model->ref
],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
'validateInitailCount'=>true,
'layoutTemplates'=>[
'actionZoom'=>'<button type="button" class="kv-file-zoom">{zoomIcon}</button>',
'actionUpload'=>'',
//'actionDelete'=>'<a>jj</a>',
//'footer' => '<div class="file-thumbnail-footer"><div class="file-caption-name" style="width:{width}">{caption}{size}</div>
//{progress}{actions}',
//'footer' => '<div class="file-thumbnail-footer"> <div class="file-caption-caption" title="{caption}"</div>'
//'actionDelete'=>'<button type="button" class="kv-file-remove"> {dataKey}{deleteUrl} {removeIcon}</button>',
],
],
'pluginEvents' => [
'filebatchselected' => 'function(event, files) {
$(this).fileinput("/products/upload-ajax");
}',
],
]);
?>
<br>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord? 'Save': 'Update', ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Cancel'), ['index', 'id' => $model->productId], ['class'=>'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I found the solution my bad
need to change all the Url::to() in controller and _form
to this format solution
The detail answer as below
_form.php
<?php
//use kartik\file\FileInput;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use backend\models\Brands;
use backend\models\Categorys;
use yii\helpers\Url;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model backend\models\Products */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="photo-library-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?php $form->errorSummary($model) ?>
<?= $form->field($model, 'ref')->hiddenInput(['maxlength' => 100])->label(false); ?>
<?= $form->field($model, 'productName')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'productDescription')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'productPrice')->textInput() ?>
<?=
$form->field($model, 'brandId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Brands::find()->where(['brandStatus'=>'active'])->all(),'brandId','brandName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a brand ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?=
$form->field($model, 'categoryId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Categorys::find()->where(['categoryStatus'=>'active'])->all(),'categoryId','categoryName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a category ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'productStatus')->dropDownList([ 'active' => 'Active', 'inactive' => 'Inactive', ], ['prompt' => 'Status']) ?>
<label>Product Images</label>
<?=
FileInput::widget([
'name' => 'upload_ajax[]',
//'attribute'=>'productImage[]',
//'name'=>'productImage[]',
'options' => [
'multiple'=>true,
'accept' => 'image/*',
//'id'=>'imageId',
],
'pluginOptions' => [
'initialPreview'=> $initialPreview,
'initialPreviewConfig'=> $initialPreviewConfig,
'showPreview' => true,
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'uploadAsync' => false,
'uploadUrl'=>Url::to('index.php?r=products/upload-ajax'),
'deleteUrl'=>Url::to('index.php?r=products/deletefile-ajax'),
'maxFileCount' => 5,
'allowedFileExtensions' => ['jpg', 'png','jpeg'],
'previewFileType' => ['jpg', 'png','jpeg'],
'overwriteInitial'=>false,
'enableResumableUpload'=>true,
'uploadExtraData' => [
'ref'=>$model->ref
],
'validateInitialCount'=>true,
'initialPreviewShowDelete' => true,
'layoutTemplates'=>[
'actionZoom'=>'<button type="button" class="kv-file-zoom">{zoomIcon}</button>',
'actionUpload'=>'',
'actionDelete' => '<button type="button" class="kv-file-remove" title="{removeTitle}" {dataKey}{dataUrl}><i class="glyphicon glyphicon-trash"></i></button>'
],
],
'pluginEvents' => [
// 'filebatchselected' => 'function(files) {
// $(this).fileinput("index.php?r=products/upload-ajax");
// }',
'filepredelete'=>'function(jqXHR){
var abort = true;
if (confirm("Are you sure you want to delete this image?")) {
abort = false;
}
return abort;
}'
],
]);
?>
<br>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord? 'Save': 'Update', ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Cancel'), ['index', 'id' => $model->productId], ['class'=>'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
ProductsController
private function getInitialPreview($ref) {
$datas = Uploads::find()->where(['ref'=>$ref])->all();
$initialPreview = [];
$initialPreviewConfig = [];
foreach ($datas as $key => $value) {
array_push($initialPreview, $this->getTemplatePreview($value));
array_push($initialPreviewConfig, [
'caption'=> $value->file_name,
'width' => '120px',
'url' => Url::to('index.php?r=products/deletefile-ajax'),
'key' => $value->upload_id
]);
}
return [$initialPreview,$initialPreviewConfig];
}

Yii2 Select2 - selected value on update - junction table (many to many)

I am successfully inserting new rows in my junction table (userlocations) on action create and I successfully update them on action update but the problem is on ation update the location_id field is always empty. It should retrieve the location_id's from userlocations table and populate the field on update but it doesnt.
Database: http://i.stack.imgur.com/JFjdz.png
UserController:
<?php
namespace backend\controllers;
use Yii;
use backend\models\User;
use backend\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use backend\models\Locations;
use backend\models\Userlocations;
class UserController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all User models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single User model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new User();
$locations = ArrayHelper::map(Locations::find()->all(), 'id', 'name');
$userlocations = new Userlocations();
if ($model->load(Yii::$app->request->post()) ) {
$model->setPassword($model->password);
$model->generateAuthKey();
$userlocations->load(Yii::$app->request->post());
if ($model->save() && !empty($userlocations->location_id)){
foreach ($userlocations->location_id as $location_id) {
$userlocations = new Userlocations();
$userlocations->setAttributes([
'location_id' => $location_id,
'user_id' => $model->id,
]);
$userlocations->save();
}
}
return $this->redirect(['user/index']);
} else {
return $this->render('create', [
'model' => $model,
'locations' => $locations,
'userlocations' => $userlocations,
]);
}
}
/**
* Updates an existing User model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$locations = ArrayHelper::map(Locations::find()->all(), 'id', 'name');
$userlocations = new Userlocations();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Userlocations::deleteAll(['user_id' => $id]);
$userlocations->load(Yii::$app->request->post());
if (!empty($userlocations->location_id)){
foreach ($userlocations->location_id as $location_id) {
$userlocations = new Userlocations();
$userlocations->setAttributes([
'location_id' => $location_id,
'user_id' => $model->id,
]);
$userlocations->save();
}
}
return $this->redirect(['user/index']);
} else {
return $this->render('update', [
'model' => $model,
'locations' => $locations,
'userlocations' => $userlocations,
]);
}
}
/**
* Deletes an existing User model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return User the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
User model:
class User extends \common\models\User
{
public $password;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'User';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['username', 'password'], 'required'],
[['status', 'created_at', 'updated_at'], 'integer'],
[['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['username'], 'unique', 'message' => 'Username already taken!'],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
}
My form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use backend\models\Locations;
?>
<div class="user-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($userlocations, 'location_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Locations::find()->all(), 'id', 'name'),
'size' => Select2::MEDIUM,
'options' => ['placeholder' => 'Select a location ...', 'multiple' => true],
'pluginOptions' => [
'allowClear' => true,
],
]); ?>
<?= $form->field($model, 'status')->dropDownList(['10' => 'Active', '0' => 'Inactive']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
For multiple location select, use the plugin code as given below.
<?= Select2::widget([
'name' => 'Userlocations[location_id]',
'value' => $location_ids, // initial value
'data' => ArrayHelper::map(Locations::find()->all(), 'id', 'name'),
'options' => ['placeholder' => 'Select your locations...', 'multiple' => true],
'pluginOptions' => [
'tags' => true,
'maximumInputLength' => 10
],
]); ?>
$location_ids will be the location array you have previously selected during creation time.Also remember when you are making changes for more than one table,make sure you do it in a transaction.

How to make validations from a query to a table? yii2

my problem is: I have a form where i have select2 and the user can select from a dropdown list which is populated from a table, so, basically what i want to happen is that when the user tries to select a driver a validation rule will take place which will check if the driver was already registered through the system that day.
I have one idea of how to do it, i have my archive form which registers people that enter in the archive table, it checks wether it exists or not in the drivers table and if not you have to register them, if they exists you proceed to fill out the form, each field in the this archive table has a datecreated column which is the date the field was entered, so basically the last time he came in.
How can i make a rule which calls for this column compares to current day and gives an error if he had already entered that day? The rule should be in drivers model.(My code is confusing that is why i'm clarifying, i'm new to Yii2)
My view (archive form):
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use wbraganca\dynamicform\DynamicFormWidget;
use app\models\Drivers;
use app\models\Vehicles;
use app\models\Invoices;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\bootstrap\Modal;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model app\models\Archive */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="archive-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'driver_identitynum')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Drivers::find()->all(),'driver_identitynum', 'fullname'),
'language' => 'en',
'options' => ['placeholder' => 'Ingrese el numero de cedula...'],
'pluginOptions' => [
'allowClear' => true],
]); ?>
<div align="right"><?= Html::a('Add driver', ['/drivers/create'],
['target'=>'_blank']); ?>
</div>
<?= $form->field($model, 'vehicle_lp')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Vehicles::find()->all(),'vehicle_lp', 'fulltruck'),
'language' => 'en',
'options' => ['placeholder' => 'Ingrese la placa del vehiculo...'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<div align="right"><?= Html::a('Add vehicle', ['/vehicles/create'],
['target'=>'_blank']); ?>
</div>
<div class="row"> <div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i>Facturas</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsInvoices[0],
'formId' => 'dynamic-form',
'formFields' => [
'invoice_number',
'invoice_loadamount',
'invoice_date',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsInvoices as $i => $modelInvoices): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Facturas</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelInvoices->isNewRecord) {
echo Html::activeHiddenInput($modelInvoices, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_number")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_loadamount")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_date", ['enableAjaxValidation' => true])->widget(DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'options' => ['class' => 'form-control picker'],
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-mm-yyyy'
]
]);?>
</div>
</div><!-- .row -->
<div class="row">
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My drivers model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "drivers".
*
* #property integer $driver_id
* #property string $driver_name
* #property string $driver_lastname
* #property string $driver_identitynum
*/
class Drivers extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'drivers';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['driver_name', 'driver_lastname', 'driver_identitynum'], 'required'],
[['driver_name', 'driver_lastname', 'driver_identitynum'], 'string', 'max' => 100]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'driver_id' => 'Driver ID',
'driver_name' => 'Driver Name',
'driver_lastname' => 'Driver Lastname',
'driver_identitynum' => 'Driver Identitynum',
];
}
public function getfullName()
{
return $this->driver_identitynum.' - '.$this->driver_name.' '.$this->driver_lastname.' ';
}
/**
* #return \yii\db\ActiveQuery
*/
public function getArchives()
{
return $this->hasMany(Archive::className(), ['driver_identitynum' => 'driver_identitynum']);
}
}
My archive model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "archive".
*
* #property integer $id
* #property string $driver_identitynum
* #property string $vehicle_lp
* #property string $DateCreated
*
* #property Invoices[] $invoices
*/
class Archive extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'archive';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['driver_identitynum', 'vehicle_lp'], 'required'],
[['DateCreated'], 'safe'],
[['driver_identitynum', 'vehicle_lp'], 'string', 'max' => 100]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'driver_identitynum' => 'Cedula del conductor:',
'vehicle_lp' => 'Placa del vehiculo:',
'DateCreated' => 'Date Created',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getInvoices()
{
return $this->hasMany(Invoices::className(), ['archive_id' => 'id']);
}
public function __toString()
{
return 'CI:'.$this->driver_identitynum.' Placa: '.$this->vehicle_lp;
}
public function didheloadtoday($attribute,$params)
{
$inputlp=($this->invoice_loadamount);
$row = (new \yii\db\Query())
->select('vehicle_lp')
->from('vehicles')
->where("vehicle_lp=$vehiclelp")
->all();
}
}
So, the rule is that only one driver_identitynum and DateCreated combination can exist in the archive table.
To validate the driver_identity field for this you can use the native unique validator and specify the attributes that need to be unique together.
The corresponding rule would be:
[['driver_identitynum'], 'unique',
'targetAttribute' => ['driver_identitynum', 'DateCreated'],
],
If this validation is called from another model, then it complicates matters a bit. In addition to the above:
specify the target class
declare a public date variable in the other model
store current date in this field
indicate the this date property should be used as value to check uniqueness of DateCreated
The adjusted rule would be:
[['driver_identitynum'], 'unique',
'targetAttribute' => ['driver_identitynum', 'date' => 'DateCreated'],
'targetClass' => '\app\models\Archive'
],

Dynamic forms operations with data on generated forms? yii2

basically. I have a problem with 2 things:
I'm using dynamic forms, the user can add as many as he needs to input all of the invoices at hand. I have a field (invoice_loadamount), i want to sum all of the invoice_loadamount fields. So if the user generates 3 forms i want it to sum dynamic form one(invoice_loadamount field 1) + dynamic form two.(invoice_loadamount field 2) + dynamic form three(invoice_loadamount field 3). How can i make this? Auto sum this field from every form he generated?
My second problem is that i want to then retrieve data from a table (vehicles, column vehicle_capacity) and then compare in such a way that it will validate if the sum is greater than the vehicle_maxcap and then give an error if so.
My form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use wbraganca\dynamicform\DynamicFormWidget;
use app\models\Drivers;
use app\models\Vehicles;
use app\models\Invoices;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\bootstrap\Modal;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model app\models\Archive */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="archive-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'driver_identitynum')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Drivers::find()->all(),'driver_identitynum', 'fullname'),
'language' => 'en',
'options' => ['placeholder' => 'Ingrese el numero de cedula...'],
'pluginOptions' => [
'allowClear' => true],
]); ?>
<div align="right"><?= Html::a('Add driver', ['/drivers/create'],
['target'=>'_blank']); ?>
</div>
<?= $form->field($model, 'vehicle_lp')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Vehicles::find()->all(),'vehicle_lp', 'fulltruck'),
'language' => 'en',
'options' => ['placeholder' => 'Ingrese la placa del vehiculo...'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<div align="right"><?= Html::a('Add vehicle', ['/vehicles/create'],
['target'=>'_blank']); ?>
</div>
<div class="row"> <div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i>Facturas</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsInvoices[0],
'formId' => 'dynamic-form',
'formFields' => [
'invoice_number',
'invoice_loadamount',
'invoice_date',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsInvoices as $i => $modelInvoices): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Facturas</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelInvoices->isNewRecord) {
echo Html::activeHiddenInput($modelInvoices, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_number")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_loadamount")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_date", ['enableAjaxValidation' => true])->widget(DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'options' => ['class' => 'form-control picker'],
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-mm-yyyy'
]
]);?>
</div>
</div><!-- .row -->
<div class="row">
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My archive model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "archive".
*
* #property integer $id
* #property string $driver_identitynum
* #property string $vehicle_lp
* #property string $DateCreated
*
* #property Invoices[] $invoices
*/
class Archive extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'archive';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['driver_identitynum', 'vehicle_lp'], 'required'],
[['DateCreated'], 'safe'],
[['driver_identitynum', 'vehicle_lp'], 'string', 'max' => 100]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'driver_identitynum' => 'Cedula del conductor:',
'vehicle_lp' => 'Placa del vehiculo:',
'DateCreated' => 'Date Created',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getInvoices()
{
return $this->hasMany(Invoices::className(), ['archive_id' => 'id']);
}
}
My vehicle model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "vehicles".
*
* #property integer $vehicle_id
* #property string $vehicle_model
* #property string $vehicle_lp
* #property string $vehicle_maxcap
*/
class Vehicles extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'vehicles';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['vehicle_model', 'vehicle_lp', 'vehicle_maxcap'], 'required'],
[['vehicle_model', 'vehicle_lp', 'vehicle_maxcap'], 'string', 'max' => 100]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'vehicle_id' => 'Vehicle ID',
'vehicle_model' => 'Vehicle Model',
'vehicle_lp' => 'Vehicle Lp',
'vehicle_maxcap' => 'Vehicle Maxcap',
];
}
public function getfullTruck()
{
return $this->vehicle_lp.' - '.$this->vehicle_model.' - '.$this->vehicle_maxcap.'kgs';
}
}
My invoice model:
<?php
namespace app\models;
use Yii;
use yii\db\Query;
/**
* This is the model class for table "invoices".
*
* #property integer $id
* #property string $invoice_number
* #property string $invoice_loadamount
* #property string $invoice_date
* #property integer $archive_id
* #property string $DateProcessed
*
* #property Archive $archive
*/
class Invoices extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'invoices';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['invoice_number', 'invoice_loadamount', 'invoice_date'], 'required'],
[['archive_id'], 'integer'],
[['DateProcessed'], 'safe'],
//[['invoice_date'],'date','format'=>'dd-mm-yyyy','min'=>date('d-m-Y',time()-60*60*24*5)],
//Checks if invoice date put in is older than 5 days
[['invoice_date'], 'date', 'format'=>"dd-MM-yyyy", 'min'=>date("d-m-Y",strtotime('-5 days'))],
[['invoice_number', 'invoice_loadamount', 'invoice_date'], 'string', 'max' => 100]];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'invoice_number' => 'Numero de factura:',
'invoice_loadamount' => 'Carga de la factura(kgs):',
'invoice_date' => 'Fecha de emision de la factura:',
'archive_id' => 'Archive ID',
'DateProcessed' => 'Fecha de registro:'];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getArchive()
{
return $this->hasOne(Archive::className(), ['id' => 'archive_id']);
}
public function compareweight($attribute,$params)
{
$inputlp=($this->invoice_loadamount);
$row = (new \yii\db\Query())
->select('vehicle_lp')
->from('vehicles')
->where("vehicle_lp=$vehiclelp")
->all();
}
}
My controller:
<?php
namespace app\controllers;
use Yii;
use app\models\Vehicles;
use app\models\VehiclesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* VehiclesController implements the CRUD actions for Vehicles model.
*/
class VehiclesController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Vehicles models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new VehiclesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Vehicles model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Vehicles model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Vehicles();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->vehicle_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Vehicles model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->vehicle_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Vehicles model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Vehicles model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Vehicles the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Vehicles::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
As you can see from the HTML <input type="text" id="invoices-0-invoice_loadamount" class="form-control" name="Invoices[0][invoice_loadamount]" maxlength="100"> the loadamount input field is like this. So on the controller side either create function or update function will receive post data as $_POST['Invoices'] as an array like
array(
"0"=>array("invoice_number" => "132412", "invoice_loadamount" =>"34.00", "invoice_date" =>"2015-03-04"),
"1"=>array("invoice_number" => "352223", "invoice_loadamount" =>"233.00", "invoice_date" =>"2016-03-04"),
...
);
where 0, 1 represents each form added. In your case form one, form two etc.
What you need to do is just loop through the array you get from the array. Like this:
if (Yii::$app->request->isPost) {
$data = Yii::$app->request->post();
$invoices = $data['Invoices'];
$total = 0;
if(sizeof($invoices) > 0){
foreach($invoices as $one_invoice){
$one_loadamount = floatval($one_invoice['invoice_loadamount']);
$total += $one_loadamount;
}
}
//then you get the total amount as $total
}
for problem 2, you can then (assume that you already have the vehicle_id).
$vehicle = Vehicles::find()->where(['id'=>$vehicle_id])->one();
if($total > $vehicle->maxcap){
\Yii::$app->getSession()->setFlash('danger', 'Total is larger than max cap');
}
Since the second problem depends on a specific vehicles, you need to get its id first.

image are save in folder but not saved in database in yii2.0

i am new in yii and i use to upload images in databse but images are stored in folder but not saved in database what is the problem with this code coud not undurstand
public function actionCreate()
{
$model = new Jobs;
// $site_url=Yii::$app->getUrlManager()->createAbsoluteUrl('');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$image = UploadedFile::getInstance($model,'image');
$imagepath='upload/jobs/';
$path=$imagepath.rand(10,100).$image->name;
if(!empty($image)){
$image->saveAs($path);
$model->image=$image->name;
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
else {
// echo "file not ulpoaded";
}
return $this->render('create', [
'model' => $model,
]);
}
model is here named as Jobs.php.
namespace app\models;
use Yii;
use yii\web\UploadedFile;
use yii\base\Model;
/**
* This is the model class for table "jobs".
*
* #property integer $id
* #property integer $users_id
* #property string $title
* #property string $deadline
* #property string $urgency
*/
class Jobs extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*
*
*/
public $image;
public static function tableName()
{
return 'jobs';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['users_id', 'title', 'deadline', 'urgency'], 'required'],
[['users_id'], 'integer'],
[['content'], 'string'],
[['deadline'], 'required'],
[['urgency'], 'string'],
[['urgency'], 'safe'],
[['image'],'file', 'skipOnEmpty'=>true,'extensions' => 'png,gif,jpg'],
[['title'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'users_id' => Yii::t('app', 'Users ID'),
'content'=>Yii::t('app','Content'),
'title' => Yii::t('app', 'Title'),
'deadline' => Yii::t('app', 'Deadline'),
'urgency' => Yii::t('app', 'Urgency'),
'image' => Yii::t('app', 'image'),
];
}
}
the view file is here named as (_form.php)
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\web\UploadedFile;
//use kartik\widgets\FileInput;
/* #var $this yii\web\View */
/* #var $model app\models\Jobs */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="jobs-form">
<?php
$form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'users_id')->textInput() ?>
<?= $form->field($model, 'content')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'deadline')->textInput() ?>
<?= $form->field($model, 'urgency')->dropDownList([ 'No', 'yes', ], ['prompt' => '']) ?>
<?= $form->field($model, 'image')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
enter code here
plzz help me to upload the image in database i dont know what the problem with this code.
change your upload code like below:
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$image = UploadedFile::getInstance($model,'image');
$imagepath='upload/jobs/';
$rand_name=rand(10,100);
if ($image)
{
$model->image = "category_{$rand_name}-{$image}";
}
if($model->save()):
if($image):
$image->saveAs($imagepath.$model->image);
endif;
endif;
return $this->redirect(['view', 'id' => $model->id]);
}
You're mixing image name and image file in your code.
public $imageis unnecessary if image is a field in your db-table. Instead add public $imageFile in your model, and update your form and controller accordingly.
Remember, $this->image, or $model->image is the name of the image as a string, you're mixing in an upload object. Instead create another variable so you can store the uploaded image in, and use the image variable for saving the actual name for later reference.
See if you can figure it out, and update your question if you can't get it to work.
http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html