Yii2 Save multiple data in the db using foreach loop in actionCreate - arrays

In my project I want to insert multiple rows of data at a single time using the foreach loop. I have a variable which has array of elements.
For instance if my array has say 3 different elements. I want to save all these 3 elements in the 3 different db table rows. I also have other columns which are same for all the 3 array elements.
I have put them inside foreach statement but only the 1st elements gets saved. Is there any method I can achieve this?
My code
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}
Only the productline_id is different other columns will have same data for all the prdouctline_id.
Thank You!!!

You have only one model object, and you are saving only to it.
Try this:
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model = new ProductlinesStorage();
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}

maybe you can modify my code
public function actionCreate()
{
$model = new SemesterPendek();
$model->user_id = \Yii::$app->user->identity->id;
$model->npm = \Yii::$app->user->identity->username;
$modelsNilai = [new Nilai];
if ($model->load(Yii::$app->request->post())){
$model->waktu_daftar = date('Y-m-d h:m:s');
$model->save();
$modelsNilai = Tabular::createMultiple(Nilai::classname());
Tabular::loadMultiple($modelsNilai, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Tabular::validateMultiple($modelsNilai) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsNilai as $indexTools =>$modelNilai) {
$modelNilai->id_sp = $model->id;
// $modelNilai->user_id = \Yii::$app->user->identity->id;
if (! ($flag = $modelNilai->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack(); \Yii::$app->session->setFlash('error','gagal');
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsNilai' => (empty($modelsNilai)) ? [new Nilai] : $modelsNilai,
]);
}
}

You need to create a different object to save in different rows. For loop executes 3 times but every time same object is being updated. You can define new object and save each time. Below code will work
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model = new ProductlinesStorage();
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}

Related

Wordpress React JS based template website not working after upgrading to PHP 8.1

After switching from PHP 7.4.30 to PHP 8.1, my WordPress website, which was built by the original developer using React JS, started acting strangely. The menus stopped working and the home page became frozen and immovable.
Enable the debug and below are some of them.
Deprecated: Optional parameter $menu declared before required parameter $location is implicitly treated as a required parameter in \app\public\wp-content\themes**\functions\classes\Settings\Menu.php on line 22
**
<?php
namespace ThemeClasses\Settings;
class Menu
{
public function __construct()
{
add_action('after_setup_theme', [$this, 'registerNavMenus']);
add_filter('getMenuTree', [$this, 'getMenuTree'], 10, 2);
}
public function registerNavMenus()
{
register_nav_menus([
'header_menu' => __('Header Menu', 'siri'),
'footer_menu' => __('Footer Menu', 'siri'),
'footer_columns' => __('Footer Columns', 'siri'),
]);
}
public function getMenuTree($menu = [], $location)
{
$flatMenu = $menu;
$flatMenu = $this->getMenuItems($menu, $location);
$treeMenu = [];
$itemsRefs = [];
foreach ($flatMenu as $menuItemObj) {
$itemId = $menuItemObj->ID;
$parentId = $menuItemObj->menu_item_parent;
$itemsRefs[$itemId] = [
'name' => $menuItemObj->title,
'url' => $menuItemObj->url,
'target' => $menuItemObj->target,
'active' => $menuItemObj->active,
'ID' => $itemId,
'parentId' => $parentId,
'children' => [],
];;
if ($parentId == 0) {
$treeMenu[] = &$itemsRefs[$itemId];
} elseif (isset($itemsRefs[$parentId])) {
$itemsRefs[$parentId]['children'][] = &$itemsRefs[$itemId];
}
}
return $treeMenu;
}
private function getMenuItems($menu, $location)
{
// Get all locations
$locations = get_nav_menu_locations();
// Get object id by location
$menuObject = wp_get_nav_menu_object($locations[$location]);
// Check menu exists
if (!is_object($menuObject)) return [];
// Get menu items by menu slug
$menu = wp_get_nav_menu_items($menuObject->slug);
// Return menu post objects
return $menu;
}
}
**Deprecated: parse_str(): Passing null to parameter #1 ($string) of type string is deprecated in public\wp-content\themes**r\functions\classes\WordPressSecurity.php on line 364
// add the filter
add_filter('wp_admin_css', function($url, $file) {
errol_log($url);
// make filter magic happen here...
return $url;
}, 10, 2 );
}
public function removeWPVersion($src)
{
global $wp_version;
parse_str(parse_url($src, PHP_URL_QUERY), $query);
if (!empty($query['ver']) && $query['ver'] === $wp_version) {
$src = remove_query_arg('ver', $src);
}
return $src;
}

save the record of bulk sms sent into db laravel

i have taken the id and mobile_num from users table.i have to insert that id name in this table as user_id,mobile_num,and status(0,1) into another table(wc_sms_status).sendSMSFunction is working fine.
public function SendBulkSms()
{
$usersNumber = User::select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
}
elseif($userNumber->mobile_num == exist && status == 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
}
else{
}
}
}
Do this :
public function SendBulkSms()
{
//assuming there is a relationship between your model users and wc_sms_status called wcSmsStatus
$usersNumber = User::with('wcSmsStatus')->select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
'user_id' => $userNumber->id,
'mobile_num' => $userNumber->mobile_num,
'status' => 1,
]);
} elseif ($userNumber->mobile_num && $userNumber['wcSmsStatus']->status === 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
} else {
}
}
}
public function SendBulkSms()
{
$users = User::select('id','mobile_num')
->whereIn('id', [5,6,7,8])
->whereNotNull('mobile_num')
->get();
$bulkData = [];
foreach ($users as $user)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
$bulkData[] = [
'user_id' => $user->id,
'mobile_num' => $user->mobile_num,
];
}
if (!empty($bulkData)) {
WcSmsStatus::insert($education); // change to your model name
unset($bulkData);
}
}
try to use in this way, it will insert bulk data, dont fergot to mention protected $fillable[] in model

how to calculate bundle product price from array of custom selection through parameter(post data)?

the data got from post is.
[productid] => 3
[product_type] => bundle
[bundle_option] => Array
(
[1] => Array
(
[0] => 1
[1] => 2
)
[2] => Array
(
[0] => 3
[1] => 4
)
)
[qty] => 1
how to calculate the bundle price for my selections. The magento core funtions are more preferable.
Please use below code:
public function getDisplayPrice($product) {
if($product->getFinalPrice()) {
return $product->getFormatedPrice();
} else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
$optionCol= $product->getTypeInstance(true)
->getOptionsCollection($product);
$selectionCol= $product->getTypeInstance(true)
->getSelectionsCollection(
$product->getTypeInstance(true)->getOptionsIds($product),
$product
);
$optionCol->appendSelections($selectionCol);
$price = $product->getPrice();
foreach ($optionCol as $option) {
if($option->required) {
$selections = $option->getSelections();
$minPrice = min(array_map(function ($s) {
return $s->price;
}, $selections));
if($product->getSpecialPrice() > 0) {
$minPrice *= $product->getSpecialPrice()/100;
}
$price += round($minPrice,2);
}
}
return Mage::app()->getStore()->formatPrice($price);
} else {
return "";
}
}
I solved it by own method, not sure its acceptable or not.
$bundle_option = Mage::app ()->getRequest ()->getParam('bundle_option');
$bundle_option_array = call_user_func_array('array_merge', $bundle_option);
$price = Mage::Helper('airhotels/bundle')->getBundlePrice($productid,$bundle_option_array);
my helper file is
public function getBundlePrice($productId,$bundle_option_array) {
$product = new Mage_Catalog_Model_Product();
$product->load($productId);
$price=0;
$selectionCollection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product);
foreach($selectionCollection as $option)
{
if (in_array($option->getSelectionId(), $bundle_option_array)){
$price += $option->price;
}
}
return $price;
}

update one field of a table from another controller while save the data

I have a manage_returns_controller and it has two action,add and index.It has one product dropdown,one stock dropdown and add button.And I also have manage_products_controller that contains a field stock.But now I want to do the following
When I click on the returns controller's add button then simultaneously save the return data as well as increase the stock in the product table.
heres the add action code
function add($id = null)
{
/*$this->pageTitle = "Edit Exchange";*/
$storeval = $this->Store->find('all',array('conditions'=>array('is_deleted'=>0,'is_blocked'=>0)));
//$storeval=$this->Store->findByName();
$storevalas = array();
foreach($storeval as $storevall)
{
$storevalas[$storevall['Store']['id']] = $storevall['Store']['name'];
}
$this->set('stock_entry_option_store', $storevalas);
//$product_name = $this->Exchange->product->find('list');
$storevaldd = $this->Product->find('all',array('conditions'=>array('is_deleted'=>0,'is_blocked'=>0)));
//$storeval=$this->Store->findByName();
$product_name = array();
foreach($storevaldd as $storevall)
{
$product_name[$storevall['Product']['id']] = $storevall['Product']['name'];
}
$this->set('stock_entry_option_product',$product_name);
$this->Return->id = $id;
if(!empty($id)){
$button_name = "Update";
$msg_act = "updated";
$this->pageTitle = "Edit Return";
} else {
$button_name = "Add";
$msg_act = "added";
$this->pageTitle = "Add Return";
}
if (empty($this->data))
{
$this->data = $this->Return->read();
}
else
{
if ($this->Return->save($this->data))
{
$this->Session->setFlash(__('Return successfully '.$msg_act.'.',true),'default',array('class' => 'success'));
$this->redirect(array('controller'=>'ManageReturns','action' => 'index'));
}
}
$this->set('button_name',$button_name);
}

Codeigniter - Array dont work correctly

Whenever I call this function, I get the user_id correctly but the password isnt checked...
Model:
<?php
class Prometheus_model extends CI_Model {
var $tables = array(
'bots' => 'bots',
'users' => 'users'
);
function __construct() {
parent::__construct();
}
public function tablename($table = NULL) {
if(! isset($table)) return FALSE;
return $this->tables[$table];
}
public function get($table, $where = array(), $order = NULL) {
$this->db->where($where);
if(isset($order)) {
$this->db->order_by($order);
}
$q = $this->db->get_where($this->tablename($table),$where);
$result = $q->result_array();
// You should use $q->num_rows() to detect the number of returned rows
if($q->num_rows()) {
return $result[0];
}
return $result;
}
public function update($table, $where = array(), $data) {
$this->db->update($this->tablename($table),$data,$where);
return $this->db->affected_rows();
}
public function insert($table, $data) {
$this->db->insert($this->tablename($table),$data);
return $this->db->insert_id();
}
public function delete($table, $where = array()) {
$this->db->delete($this->tablename($table),$where);
return $this->db->affected_rows();
}
public function explicit($query) {
$q = $this->db->query($query);
if(is_object($q)) {
return $q->result_array();
} else {
return $q;
}
}
public function num_rows($table, $where = NULL) {
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
public function get_bot_data_by_hw_id($bot_hw_id) {
$q = $this->get('bots', array('bot_hw_id' => $bot_hw_id));
return $q;
}
public function check_user_data($user_incredials, $user_password) {
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1){
$q = $this->get('users', array('user_name' => $this->security->xss_clean($user_incredials)));
return $q['user_id'];
}
return FALSE;
}
}
?>
My function-calling at the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index(){
if($this->input->post('user_login')){
var_dump($this->prometheus_model->check_user_data($this->input->post('user_incredials'), $this->input->post('user_password')));
}
$this->load->view('login_index');
}
}
How can i fixx this ?
In your check_user_data() method you are using
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1)
I think (logically) following code
$this->encrypt->decode($user_password)
should be
$this->encrypt->encode($user_password)
because, you are calling num_rows() method and it is
public function num_rows($table, $where = NULL)
{
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
which is actually querying the data base something like, for example,
select * from USERS where user_name = 'heera' and password = decode('abcde12345')
In this case, the password you are trying to match is need to be encrypted using encode (not decode) method, because the user has given you a non-encrypted (plain) password and the password saved in the database is already encrypted, so encode the plain password using encode method before you query the database to match with already encoded passwords.

Resources