How the query used in Yii2 - yii

Can you help me. i want to like example but on my source code it becomes empty emty. What is the query or source code in my project? thank You.
in Controller
public function actionView($id)
{
$con = Yii::$app->db;
$sql = $con->createCommand("SELECT * FROM track where collecting_id=$id ORDER BY collecting_id desc");
$posts = $sql->query();
return $this->render('view', [
'model' => $this->findModel($id),
'posts' => $posts,
]);
}
in View
<div class="timeline__items">
<?php
foreach($posts as $row)
{
?>
<div class="timeline__item">
<div class="timeline__content">
<h2><?php echo $row['status']; ?></h2>
<p><?php echo $row['tanggal']; ?></p>
</div>
</div>
<?php
}
?>
</div>
if the $id on the query is replaced with 'PMUEI' the result is result
Use ActiveDataProvider
public function actionView($id)
{
$model = $this->findModel($id);
$hotel = Track::find()->where(['collecting_id' => $model->collecting_id]);
$posts = new ActiveDataProvider([
'query' => $hotel,
]);
// $con = Yii::$app->db;
// $sql = $con->createCommand(
// "SELECT * FROM track where collecting_id=:collecting_id ORDER BY collecting_id desc",
// [':collecting_id' => '$id']
// );
// $posts = $sql->queryAll();
return $this->render(
'view', [
'model' => $this->findModel($id),
'posts' => $posts,
]);
}
the result is error .

Its always good to bind parameters when comparing columns with any such input that is provided by the user or can be edited by the user as in your case is the $id that you are passing as a parameter to the actionView(). And then you need to use queryAll() or queryOne() in case you want multiple or single rows returned.
So you should change your query to the following
public function actionView($id)
{
$con = Yii::$app->db;
$sql = $con->createCommand(
"SELECT * FROM track where collecting_id=:collecting_id ORDER BY collecting_id desc",
[':collecting_id' => $id]
);
$posts = $sql->queryAll();
return $this->render(
'view', [
'model' => $this->findModel($id),
'posts' => $posts,
]
);
}
Apart from the above, you should use ActiveRecord. Active Record provides an object-oriented interface for accessing and manipulating data stored in databases. Read Here to make your life easier.

Related

yii dependent dropdown is not working

This is my view page
<?php echo $form->dropDownListRow($order,'area_id',Area::model()->getActiveAreaList(),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/getdeliveryforarea'),
'update'=>'#pickup_time_slot', //selector to update
'data' => array('area_id' => 'js:this.value',),
)));
?>
<?php echo $form->dropDownListRow($order,'pickup_time_slot',array(),array('prompt'=>'Select time')); ?>
and in my controll the getdeliveryforarea is like
public function actionGetdeliveryforarea()
{
$data=Areatimeslot::model()->findAll('area_id=:area_id',
array(':area_id'=>(int) $_POST['id']));
$data=CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
here my dependent dropdown is not working ,from getActiveAreaList i will get the area list in first dropdown and once i choose an area it must show corrosponding time list in second dropdown,i hope someone will help me out,thanks in advance
Use Juqery migrate plugin or try something like,
jQuery.browser = {};
(function () {
jQuery.browser.msie = false;
jQuery.browser.version = 0;
if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
jQuery.browser.msie = true;
jQuery.browser.version = RegExp.$1;
}
})();

yii2 Dimensions to be validated and display the error message in the form

In yii2 project I have my own file structure setup. Anything uploaded will get saved as a file type. I can get the file dimensions using the file uploaded in the temp folder by yii2. Using those dimensions I set my own width and height and compare them. If the height and width is more than what I have declared It has display an error message in the form. Which I am unable to do it.
My Active Form
<div class="company-form">
<?php
$form = ActiveForm::begin([
'action'=>['company/logo', 'id'=>$model->company_id],
'validateOnSubmit' => true,
'options' =>
['enctype' => 'multipart/form-data','class' => 'disable-submit-buttons','id'=> 'companyLogoForm'],
'fieldConfig' => [
'template' => "<div class=\"row\">
<div class=\"col-xs-6 margin-top-8\">{label}</div>\n<div class=\"col-xs-6 text-right\">{hint}</div>
\n<div class=\"col-xs-12 \">{input}</div>
</div>",
],
]); ?>
<?= $form->errorSummary($model, $options = ['header'=>'','class'=>'pull-left']); ?>
<?= $form->field($model, 'company_name')->hiddenInput(['maxlength' => true])->label(false) ?>
<?= $form->field($file, 'file')->fileInput([])->label(Yii::t('app', 'Attach Logo'),['class'=> 'margin-top-8']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Save') : Yii::t('app', 'Save'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary','data' => ['disabled-text' => 'Please Wait']]) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My Controller Action
public function actionLogo($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$file = new File;
$file->load(Yii::$app->request->post());
$a = UploadedFile::getInstance($file,'file');
$size = getimagesize($a->tempName);
$maxWidth = 500;
$maxHeight = 500;
if ($size[0] > $maxWidth || $size[1] > $maxHeight)
{
$model->addError('file', $error = 'Error Message');
if($model->hasErrors()){
return ActiveForm::validate($model);
}
}
$file->file = UploadedFile::getInstance($file,'file');
$file->file_name = $file->file->name;
$file->file_user = Yii::$app->user->id;
$file->file_type = 1;
if($file->save()){
$file->file_path = Files::getFilePath($file->file_id);
$validDir = $file->file->createFileDir($file->file_path, $file->file_id);
if($validDir){
$file->file->saveAs($file->file_path, false);
if($file->save()){
$model->company_file = $file->file_id;
$model->save();
return $this->redirect(['index']);
}
}
}
}
}
How do I add error message in the controller and pass that to display on my form on the modal box.
Note: my form is displayed on the modal box.
Thank you!!
You should handle the file processing in your model - or even better, create a specific UploadForm model for this purpose.
In that case you can use File Validation or a custom validator to set errors during model validation.
The built-in yii\validators\FileValidator gives you plenty pf validation rules out of the box.
This is actually pretty well explained in the documentation: Uploading Files
See also the documentation for FileValidator
Example for validating an uploaded image file:
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
Try this validation rule
['imageFile', 'image', 'minWidth' => 250, 'maxWidth' => 250,'minHeight' => 250, 'maxHeight' => 250, 'extensions' => 'jpg, gif, png', 'maxSize' => 1024 * 1024 * 2],

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

Yii2: Images stored in different tables

Here my controller:
$model = new VehicleType();
if ($model->load(Yii::$app->request->post())) {
if($model->validate()){
$model->save();
$id = $model->id;
$model->file = UploadedFile::getInstance($model, 'file');
if($model->file){
$id = $model->id;
$imageName = "vehicletype_".$id.'_'.getdate()[0];
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$station = VehicleType::findOne($id);
$station->image = '#web/uploads/'.$imageName.'.'.$model->file->extension;
$station->save();
}
return $this->redirect(['vehicletype/index']);
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
My view:
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'description')->textarea() ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My model:
public function rules()
{
return [
[['description'], 'string'],
[['record_status'], 'integer'],
[['name', 'image'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'description' => 'Description',
'image' => 'Image',
'record_status' => 'Record Status',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getVehicles()
{
return $this->hasMany(Vehicles::className(), ['vehicle_type_id' => 'id']);
}
}
With this I can upload only one picture/post, I want one post to have multiple pictures, so I create a new table call 'Image' to stored my pictures and have a one-to-many relationship.
But I run into a problem, how can I add data to 2 tables from just 1 form
I'm using Yii2 basic template
Thanks
Step 1
First create two variables in your vehicletype model.
public $uploadedImages;
public $imageforNewtable = array();
Step 2
Make sure to mention this imageforNewtable variable in your model rule.
[['imageforNewtable'], 'image', 'extensions' => 'png, jpg, JPEG'],
Step 3
In your form:
<?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'imageforNewtable[]')->fileInput(['accept' => 'image/*']); ?>
Step 4
In Your Controller:
$model->uploadedImages = UploadedFile::getInstances($model,'imageforNewtable');
// Make sure to put "Instances" (plural of Instance) for uploading multiple images
$model->imageforNewtable = array(); // To avoid blank entries as we have entries in $_FILES not in $_POST.
foreach ($model->uploadedImages as $singleImage)
{
$model->imageforNewtable[] = time() . '_' . $singleImage->name;
}
Now bulk insert data in Images table :
$bulkInsertforimages = array(); //defined benchInsert array for images
$columnsArray = ['blog_id', 'image']; //Column names in which bulk insert will take place.
if ($model->imageforNewtable != '') {
foreach ($model->imageforNewtable as $singleData) {
$bulkInsertforimages[] = [
'blog_id' => $model->id,
'image' => $singleData,
];
}
}
if (count($bulkInsertforimages) > 0) {
$command = \Yii::$app->db->createCommand();
$command->batchInsert('YOUR_IMAGE_TABLE', $columnsArray, $bulkInsertforimages)->execute();
}

Trouble passing SQL data to view in codeigniter

I have a form that I am using to allow people to input data and then upload a preset picture. I want to label that picture as the form_id. I am able to run a LAST_INSERT_ID() query and display it after I insert the form in my view but I can't seem to echo that information out anywhere else. I need the query to select_last_id to run after my $update query or the ID number will be off. Could anyone assist in helping me pass just the value of the row to my view? Here is the code from my controller.
function inspection() {
if($this->input->post('submit')) {
$array = array(
'trlr_num' => $this->input->post('trlr_num'),
'seal' => $this->input->post('seal'),
'damaged' => $this->input->post('damaged'),
'truck_num' => $this->input->post('truck_num'),
'driver_name' => $this->input->post('driver_name'),
'car_code' => $this->input->post('car_code'),
'origin' => $this->input->post('origin'),
'lic_plate' => $this->input->post('lic_plate'),
'del_note' => $this->input->post('del_note'),
'live_drop' => $this->input->post('live_drop'),
'temp' => $this->input->post('temp'),
'level' => $this->input->post('level'),
'ship_num' => $this->input->post('ship_num'),
'trlr_stat' => $this->input->post('trlr_stat'),
'comment' => $this->input->post('comment')
);
$update = $this->trailer_model->insert_form($array);
$query = $this->trailer_model->select_last_id();
$result =& $query->result_array();
$this->table->set_heading('ID');
$data['table'] = $this->table->generate_table($result);
unset($query,$result);
}
$level = $this->trailer_model->select_fuel_level();
$result = $level->result_array();
$data['options'] = array();
foreach($result as $key => $row) {
$data['options'][$row['level']] = $row['level'];
}
unset($query,$result,$key,$row);
$data['label_display'] = 'Fuel Level';
$data['field_name'] = 'level';
$status = $this->trailer_model->select_trailer_type();
$result = $status->result_array();
$data['options1'] = array();
foreach($result as $key => $row) {
$data['options1'][$row['trlr_stat']] = $row['trlr_stat'];
}
unset($query,$result,$key,$row);
$data['label_display1'] = 'Trailer Status';
$data['field_name1'] = 'trlr_stat';
$data['page_title'] = 'Trailer Inspection';
$data['main_content'] = 'dlx/inspection/trailer_inspection_view';
return $this->load->view('includes/template',$data);
}
}
Anything you want to display on a view, you must pass to it.
When you're setting $data, you missed adding $query to it.
Controller:
I understand that $query = $this->trailer_model->select_last_id(); is returning just an ID, so:
$data['last_id'] = $query;
But if $query = $this->trailer_model->select_last_id(); does not return just an ID, but an array or something else, you shall include to return the ID in your model method. Actually, it'd be crucial to know what $this->trailer_model->select_last_id(); is returning.
View:
echo $last_id; -> must echo the last ID, if select_last_id() method from your model returns what it has to return.