I have a form where a user can enter different prices for products. The user can update prices too. The form looks like this:
I have two arrays, wherein one the Id is stored and in the other Prices.
So far, I have been able to reach this...
if(isset($_POST['addprice']))
{
$id = $_REQUEST['id'];
$price = $_REQUEST['price'];
foreach ($price as $key => $val) {
$priceds=$price[$key];
$idds=$id[$key];
if(!empty($priceds)){
$command = $connection->createCommand('UPDATE businessitemots SET price='.$priceds.' WHERE id='.$idds.'');
$command->execute();
}
}
$this->redirect('index',[
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]);
}
My problem is that the values are not getting updated in the DB. Can you point me in the right direction?
Related
Hello everyone :slight_smile:
i try to show 2 gridviews of datas.
a first gridview where any of three fields is empty (so if one or two of thoses fields are empty, it should show the entry)
and a second gridview with the records that have those 3 fields filled up.
i do something wrong, because if the date field is entered, then the record goes from the first to the second gridview, event if the 2 other fields remain empty…
this is my code :
(dataprovider is the second gridview and unprocessed is the first)
if(Yii::$app->user->can('admin')){
$searchModel = new DeliverySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->orderBy(['delivery_expedition_date'=>SORT_DESC]);
}
elseif(Yii::$app->user->can('maker')){
$maker = Maker::find()->where(['user_id'=>Yii::$app->user->identity->id])->one();
$searchModel = new DeliverySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['maker_id'=>$maker->id]);
//$dataProvider->query->where(['and',['not',['delivery_trackcode' => null,'delivery_carrier' => null,'delivery_expedition_date' => null]]]);
$dataProvider->query->andWhere(['not', ['delivery_trackcode' => null]]);
$dataProvider->query->andWhere(['not', ['delivery_carrier' => null]]);
$dataProvider->query->andWhere(['not', ['delivery_expedition_date' => null]]);
$dataProvider->query->orderBy(['delivery_expedition_date'=>SORT_DESC]);
$unProcessed = $searchModel->search(Yii::$app->request->queryParams);
$unProcessed->query->andWhere(['maker_id'=>$maker->id]);
$unProcessed->query->andWhere(['or',['delivery_trackcode'=> NULL],['delivery_carrier'=> NULL],['delivery_expedition_date'=> NULL]]);
$unProcessed->query->orderBy(['created_at'=>SORT_DESC]);
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'unProcessed' => $unProcessed,
]);
Any help would be very much appreciated :slight_smile:
kind regards
So, i finally found the solution. the expedition date need to be check if NULL or not, but the carrier and trackcode need to be checked for empty ('') and not for NULL
->query->andWhere(['not', ['delivery_trackcode' => null]]);
->query->andWhere(['not', ['delivery_carrier' => null]]);
I am working on a project in yii2. I need to place an input field on the index page. This field should be similar to the form field. i.e. the type of the field that is used in the form while creating a record. For this, I have done the following
public function actionIndex()
{
$model = MdcmetercustRel::className();// this is the class whose data field I want to get
$searchModel = new MdcmetersdataSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
My index
<?=
$form = ActiveForm::begin();
$relModel=$model->getModels()[0]; print_r($relModel['cust_id']);
$form->field($relModel, 'cust_id')->textInput()
?>
When I refresh my page I am getting
Object of class yii\widgets\ActiveForm could not be converted to string
How can I achieve this?
Any help would be highly appreciated
Your mistake is <?=which is trying to output the whole script and you cant echo $form or ActiveForm::begin()
change it to
<?php
$form = ActiveForm::begin();
$relModel=$model->getModels()[0]; print_r($relModel['cust_id']);
echo $form->field($relModel, 'cust_id')->textInput()
?>
Also you need to change the
$model = MdcmetercustRel::className();
to
$model = new MdcmetercustRel();
otherwise there wont be an object in $model but a string i.e class namespace.
I use laravel 5.6
I have a json file containing 500 thousand records. I want to create a logic to check whether the id of each record already exists or not in the database. If it doesn't already exist, then there will be a data insert process. If it already exists, there will be a data update process
I have made logic. I just want to make sure whether my logic is effective or not
My logic code like this :
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
$data = \DB::table('details')->where('id', '=', $value['Code'])->get();
if ($data->isEmpty()) {
\DB::table('details')->insert(
[
'id' => $value['Code'],
'number' => $value['Number'],
...
]
);
}
else {
\DB::table('details')
->where('id', '=', $value['Code'])
->update([
'id' => $value['Code'],
'number' => $value['Number'],
...
]);
}
}
The code is working. But the process seems really long
Do you have another solution that is better?
updateOrCreate
You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model, so there's no need to call save():
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
in your case your code should be like this (create Details model first) :
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
Details::updateOrCreate(
[ 'id' => $value['Code'] ],
[ 'number' => $value['Number'], ... ]
);
}
i think that's the best way to do it. Eloquent return's a collection so you cant just validate that your string is null.
here is code of dropdownlist.. but when I select multiple values it gives validation error "task must be string"
how to save multiple values (array)?
<?php echo $form->field($model, 'task')->widget(Select2::classname(), [
'data' => $companiesList,
'options' => ['placeholder' => 'Select company...','multiple' => true],
'pluginOptions' => ['allowClear' => true,],
]);?>
how to give checkbox for each value in list?
you have to save multiple values in many-to-many tabels ,
after changing the rules to [['task'], 'safe'] from Mr Skull answer , you have to get all data like this :
foreach ( $model->task as $single_task){
$task = new _many_to_many_model();
$task->side_1_id = single_task;
$task->side_2_id = $model->id;
$task->save();
}
after this comment :
all selected value should go in single column
you don't need to use many-to-many !
I use "-" as delimiter,
$all_taskes = "";
foreach ( $model->task as $single_task){
$all_taskes .= single_task."-";
}
$model->task = all_taskes;
Hi there ,
$model->save();
foreach ($model->task as $cat) {
$m = new \common\models\_many_to_many_model();
$m->ads_id = $model->id; // change in to yorr base model ID and use it's put after $model->save
$m->category_id = $cat; // category_id is your many to many model filed id
$m->save();
}
I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).