I made "gearbox"-dropDownList in my Yii webapp, all works perfect, it stores in DB with next values ( 1=> Manual, 2=> Manual-Automat(tiptronick), 3=> Automat), and now i display it in template (view.php) with such not beautiful if-block:
Gearbox:
"
if ($model->gearbox == 1) {
echo 'Manual';
} elseif($model->gearbox == 2) {
echo 'Manual-Automat';
} else {
echo 'Automat';
}
"
Tell me please, should I prepare such data in controller? And if it is possible, can you advice me, please, how it doing.
A other option would be to add this to your model with a virtual attribute, like this:
public function getGearboxName() {
if ($model->gearbox == 1) {
return 'Manual';
} elseif($model->gearbox == 2) {
return 'Manual-Automat';
} else {
return 'Automat';
}
}
This way you can access the value by the gearboxName attribute in your model:
echo $model->gearboxName;
I think in this simple case there is not much to do, but you could prepare it in your controller like this:
Controller:
if ($model->gearbox == 1) {
$gearbox = 'Manual';
} elseif($model->gearbox == 2) {
$gearbox = 'Manual-Automat';
} else {
$gearbox = 'Automat';
}
$this->render('view',array('gearbox'=>$gearbox))
View:
echo $gearbox;
Related
How to detect postProcess PrestaShop 1.6 EDIT/ADD/DELETE mode?
I have code, something like this (detect edit not working...):
detect add - is ok
detect delete - is ok
<?php
public function postProcess()
{
if (Tools::isSubmit('deletems_admin_delivery_manager') && Tools::getValue('id_ms_admin_delivery_manager') != '')
{
$this->errors[] = Tools::displayError('DETECT DELETE');
} elseif (Tools::isSubmit('submitAdminDeliveryManager')) {
if (!$id_ms_admin_delivery_manager = Tools::getValue('id_ms_admin_delivery_manager')) {
$this->errors[] = Tools::displayError('DETECT ADD');
// this not working...
} elseif($id_ms_admin_delivery_manager = Tools::getValue('id_ms_admin_delivery_manager')) {
$this->errors[] = Tools::displayError('DETECT EDIT - NOT WORKING');
}
}
}
Replace = by == in your last condition.
Of course, you don't really need the third condition:
$obj = $this->loadObject(true);
if (Tools::isSubmit('deletems_admin_delivery_manager') && $obj->id)
{
$this->errors[] = Tools::displayError('DETECT DELETE');
} elseif (Tools::isSubmit('submitAdminDeliveryManager')) {
if (#$obj->id) {
$this->errors[] = Tools::displayError('DETECT EDIT');
} else {
$this->errors[] = Tools::displayError('DETECT ADD');
}
}
UPDATE:
also you can use the Prestashop methods:
public function processDelete()
{
//Delete
}
public function processSave()
{
//Add or Update
}
public function processAdd()
{
//Add
}
public function processUpdate()
{
//Update
}
There is an error Undefined Variable when running my Model Class:
public $accountTypeFlag;
.......
public function getSecondType() {
if (($this->$accountTypeFlag == 1)){
return array (self::CURRENT_ASSETS=>'Current Assets',self::PROPERTY_AND_EQUIPMENT=>'Property and Equipment',self::OTHER_ASSETS=>'Other Assets');
}
if (($accountTypeFlag == 2)){
return array (self::CURRENT_LIABILITIES=>'Current Liabilities');
}
if (($accountTypeFlag == 3)){
return array (self::FUND_BALANCE=>'Fund Balance');
}
}
Is there any way to read the accountTypeFlag inside the function?
public $accountTypeFlag;
...
public function getSecondType() {
if ($this->accountTypeFlag == 1) {
...
} elseif ($this->accountTypeFlag == 2) {
...
} elseif ($this->accountTypeFlag == 3) {
...
}
}
i want use where for $query.
foreach ($oppId as $o) {
$id = $o['opportunity_id'];
$query->Where("id=$id");
}
When I use this. All items shown
$query->orWhere("id=$id");
i need get this query :
SELECT * FROM `opportunity` WHERE id =27 or id =28
this is all of my function :
public function actionShow($type = 0, $city = 0, $client = 0) {
$query = (new \yii\db\Query())->select(['*'])->from('opportunity ')->innerJoin('profile_details', 'opportunity.user_id=profile_details.user_id')->orderBy('id desc');
$query->Where('id !=-1');
if (isset($_REQUEST['type'])) {
$type = $_REQUEST['type'];
if ($type != 0) {
$query->andWhere("project_type_id=$type");
}
}
if (isset($_REQUEST['city'])) {
$city = $_REQUEST['city'];
if ($city != 0) {
$query->andWhere("state_id=$city");
}
}
if (isset($_REQUEST['client'])) {
$client = $_REQUEST['client'];
if ($client != 0) {
$oppId = \app\models\OpportunityControl::find()
->where('project_type_id = :project_type_id', [':project_type_id' => $client])
->all();
foreach ($oppId as $o) {
$id = $o['opportunity_id'];
$query->orWhere("id=$id");
}
}
}
You very much do not want to use strings to add to the query under any circumstances as that is ripe for SQL injection. I'd format it like this:
...
$params = [];
foreach ($oppId as $o) {
$params[] = $o->opportunity_id;
}
$query->andWhere(['in', 'id', $params]);
...
You should also adjust your other query params so that you are not passing variables into SQL via a string.
if (isset($_REQUEST['type'])) {
$type = $_REQUEST['type'];
if ($type != 0) {
$query->andWhere(['project_type_id' => $type]);
}
}
if (isset($_REQUEST['city'])) {
$city = $_REQUEST['city'];
if ($city != 0) {
$query->andWhere(['state_id' => $city]);
}
}
See the Yii2 guide on using variables in queries for what you are trying to avoid here. Specifically:
Do NOT embed variables directly in the condition like the following, especially if the variable values come from end user inputs, because this will make your application subject to SQL injection attacks.
// Dangerous! Do NOT do this unless you are very certain $status must be an integer.
$query->where("status=$status");
I do it with Arrays
$query->where(['or',['id'=>27],['id'=>28]]);
But in your case save all ids in a Array is not possible,I do it with string inside foreach
$StringWhere='';
$LastElement = end($oppId);
foreach ($oppId as $o)
{
$id = $o['opportunity_id'];
$StringWhere.=' id='.$id;
if($o!=$LastElement)
{
$StringWhere.=' or ';
}
}
$query->where($StringWhere);
$query->where(['or',['id'=>27],['id'=>28]]);
I use this and it works perfectly as mentioned by metola. :)
For one action I need transform $album_id before save it to DB
in model function beforeSave() i do:
// преобразовать album -> album_id
$album_id=array();
foreach($this->string2array($this->album, '\|') as $one)
$album_id[]=Album::model()->findByAttributes(array('album' => $one))->id;
$this->album_id = $this->array2string($album_id);
but for another action I don't need this transform, because $album_id is already in proper state. So I set scenario 'batchcreate' in that action:
public function actionCreate()
{
Yii::import('ext.multimodelform.MultiModelForm');
$model = new Album('create');
$song = new Song();
$song->setScenario('batchcreate');
...
}
and try to check this scenario in model:
if(!($this->scenario === 'batchcreate')) {
// преобразовать album -> album_id
$album_id=array();
foreach($this->string2array($this->album, '\|') as $one)
$album_id[]=Album::model()->findByAttributes(array('album' => $one))->id;
$this->album_id = $this->array2string($album_id);
}
but the condition is always true. Why my scenario doesn't set or doesn't check in if statement?
Or maybe it's better to check not scenario, but make another variable, so how to set its value for 2 different cases?
my whole beforeSave():
protected function beforeSave()
{
if(parent::beforeSave())
{
// преобразовать whoes -> who
$who=array();
foreach($this->string2array($this->whoes) as $one) {
$userrow = User::model()->findByAttributes(array('username' => $one));
if($userrow) $who[]=CHtml::encode($userrow->id);
else $who[]=$one;
}
$this->who = $this->array2string($who);
//var_dump( $this->scenario );
if(!($this->scenario == 'batchcreate')) {
//if($this->notbatchcreate == 'yes') {
// преобразовать album -> album_id
$album_id=array();
foreach($this->string2array($this->album, '\|') as $one)
$album_id[]=Album::model()->findByAttributes(array('album' => $one))->id;
$this->album_id = $this->array2string($album_id);
}
return true;
}
else
return false;
}
Instead of
$song = new Song();
$song->setScenario('batchcreate');
you can simply do
$song = new Song('batchcreate');
In beforeSave()
if ( $this->scenario != 'batchcreate' ) {
echo "good - scenario is not batchcreate";
die();
}
echo 'nope...';
var_dump($this->scenario);
die();
Switch the order: call parent::beforeSave() after your code for checking the scenario. The inherited method beforeSave() may be altering your scenario.
I made my own class that extends CBaseUrlRule to manage some sort of pages on site. Result class code is
class HotelUrlRule extends CBaseUrlRule {
public function parseUrl($manager,$request,$pathInfo,$rawPathInfo) {
if(isset($_GET['id'])) {
if (($_GET['id'] != 0) && ($pathInfo == 'hotel')) {
return 'hotel/index';
}
}
return false;
}
public function createUrl($manager,$route,$params,$ampersand) {
if ($route == 'hotel/index') {
Yii::import('application.controllers.SearchController');
$searcher = new SearchController($this, NULL);
$hotelRaw = $searcher->actionGetHotelInformation($_GET['id']);
$hotelRaw = $hotelRaw['GetHotelInformationResult'];
$hotelName = $hotelRaw['Name'];
$hotelName = preg_replace('%(\s)%', '-', $hotelName);
return 'hotel/' . $hotelName;
}
return false;
}
}
The condition in parseUrl ($_GET['id'] != 0) && ($pathInfo == 'hotel') returns 'true' and the condition in createUrl ($route == 'hotel/index') returns 'false'. Var_dump of $route is 'admin/auth'.
Why is it so? Any guesses?