I have a simple question that needs to get an element when selecting that reference ID by an input form. I used the following code to do that.
$id2=$locationProducts[0]->inventory_update_stock_details_id;
But this code outs only the first element always. AS an exmple inventory_update_stock_details_id=36, inventory_update_stock_details_id=36, inventory_update_stock_details_id=36 and so on.
But I needs to select as inventory_update_stock_details_id=35, inventory_update_stock_details_id=345, inventory_update_stock_details_id=2 like that.
inventory_update_stock_details_id included ids as 1,2,3,4,5,......1000
The model as follows :
function getInventoryLocationProducts()
{
$this->db->select("*");
$this->db->from('store_inventory_update_stock_details');
$this->db->join('store_inventory_item', 'store_inventory_item.inventory_item_id=store_inventory_update_stock_details.inventory','left');
$this->db->join('store_inventory_location_update', 'store_inventory_location_update.inventory_update_stock_id=store_inventory_update_stock_details.inventory_update_stock_id','left');
$this->db->join('store_inventory_update_stock', 'store_inventory_update_stock.inventory_update_stock_id=store_inventory_location_update.inventory_update_stock_id','left');
$this->db->where('store_inventory_item.status=1');
$this->db->where('store_inventory_update_stock_details.serial_no NOT IN (select serial_no from store_inventory_location_update)');
$q = $this->db->get_where();
if ($q->num_rows() > 0) {
return $q->result();
}
return FALSE;
}
Controller
public function addInventoryLocation()
{
$this->checkPermissions('add', 'inventoryLocation');
$bc = array(array('link' => '#', 'page' => 'Inventory Locations'));
$meta = array('page_title' => 'Inventory Locations', 'bc' => $bc);
$this->data['branch'] = $this->Item_model->getBranch();
$this->data['office'] = $this->Item_model->getOffice();
$locationProducts = $this->Item_model->getInventoryLocationProducts();
$this->data['locationProducts'] = $locationProducts;
$this->data['auto_loc_no'] = $this->Item_model->generate_inv_loc_ref();
$count = $this->input->post('i');
$str = $this->input->post('auto_loc_no');
$auto_loc = preg_replace("/[^0-9]{1,4}/", '', $str);
$this->form_validation->set_rules('branch', 'Branch', 'required');
if ($this->form_validation->run() == true) {
$stock = array(
'office_id' => $this->input->post('office'),
'branch' => $this->input->post('branch'),
'l_date' => $this->input->post('l_date'),
'is_order_no' => $this->input->post('is_order_no'),
'loc_no' => $this->input->post('auto_loc_no'),
'auto_loc_no' => $auto_loc,
'user' => ucfirst($this->session->userdata('name')),
'order_status' => 'locate',
'status' => 1
);
$id = $this->Item_model->addInventoryLocation($stock);
}
$id2=$locationProducts[0]->inventory_update_stock_details_id;
dd($id2);
if ($this->form_validation->run() == true && $id2 != 0) {
$count = $this->input->post('i');
for ($x = 0; $x <= $count; $x++) {
$details[$x]['inventory_update_stock_id'] = $id2;
$details[$x]['inventory'] = $this->input->post('inventory' . $x);
$details[$x]['serial_no'] = $this->input->post('serial_no' . $x);
$details[$x]['item_code'] = $this->input->post('item_code' . $x);
$details[$x]['officer'] = $this->input->post('officer' . $x);
$details[$x]['qty'] = 1;
$details[$x]['status'] = 1;
$details[$x]['branch'] = $this->input->post('branch');
}
if ($this->Item_model->addInventoryLocationDetails($details)) {
echo("<meta http-equiv='refresh' content='1'>");
$this->session->set_flashdata('message', 'Successfully Added ..!!');
redirect('item/addInventoryLocation');
}
} else {
$this->session->set_flashdata('error', validation_errors());
$this->render('item/addInventoryLocation', $meta, $this->data);
}
}
View
<td style="width: 30%">
<input type="hidden" name="i" id="i" value="0">
<select name="inventory0" id="inventory0" class="form-control select2 inventory-select" required>
<option value=""></option>
<?php
if (!empty($locationProducts)) {
foreach ($locationProducts as $row) {
echo "<option value='".$row->inventory_update_stock_details_id."'> $row->inventory_update_stock_details_id - $row->inventory_item_name</option>";
?>
<?php
}
}
?>
</select>
</td>
What can modify my code line to do that. Can anyone help me ?
I'm not entirely sure what the intended logic is, but I think what you want is to add the InventoryLocationDetails to all InventoryLocationProducts.
If that is correct, you could perhaps do something like this:
if ($this->form_validation->run() == true) {
$details = [];
foreach ($locationProducts as $locationProduct) {
$id2 = $locationProduct->inventory_update_stock_details_id;
$count = $this->input->post('i');
for ($x = 0; $x <= $count; $x++) {
$details[] = [
'inventory_update_stock_id' => $id2,
'inventory' => $this->input->post('inventory' . $x),
'serial_no' => $this->input->post('serial_no' . $x),
'item_code' => $this->input->post('item_code' . $x),
'officer' => $this->input->post('officer' . $x);
'qty' => 1,
'status' => 1,
'branch' => $this->input->post('branch'),
];
}
}
if ($this->Item_model->addInventoryLocationDetails($details)) {
echo("<meta http-equiv='refresh' content='1'>");
$this->session->set_flashdata('message', 'Successfully Added ..!!');
redirect('item/addInventoryLocation');
}
}
This assumes that $locationProducts contains only those products that actually need to be updated. If you need to only update some of them, you can add the logic to determine which product to update inside the foreach loop.
Related
i have a problem where i want to update a looping form in codeigniter 3. in column nik_pindah where have a id_surat is same
---MY CONTROLLER WITH FORM VALIDATION---
public function update_nik_pindah_kelurahan($id_surat_pindah){
$this->load->library('form_validation');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null){
foreach ($a as $row => $val){
$this->form_validation->set_rules("nik_pindah[$i]","nik_pindah", "integer|callback_nik_pindah_available");
}
}
$this->form_validation->set_message('required', 'Mohon isi %s terlebih dahulu');
$this->form_validation->set_message('integer', 'Isi %s hanya menggunakan angka');
if ($this->form_validation->run() == FALSE){
$this->edit_nik_pindah_kelurahan($id_surat_pindah);
} else {
$id_surat_pindah = $this->input->post('id_surat_pindah');
$id_surat = $this->input->post('id_surat');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null) {
$data = array(
'id_surat' => $id_surat,
'id_surat_pindah' => $id_surat_pindah
);
foreach ($a as $row) {
$dataaa = [
'id_surat' => $id_surat_pindah,
'nik_pindah' =>$row,
];
$wheree = array(
'id_surat' => $id_surat_pindah
);
$this->db->where('id_surat', $id_surat_pindah);
$update = $this->db->update('nik_pindah', $dataaa);
if ($update) {
$i++;
}
}
$where = array(
'id_surat_pindah' => $id_surat_pindah
);
$this->m_pindah_kelurahan->update_data($where, $data, 'surat_pindah');
}
redirect('admin_pindah_kelurahan/index');
}
}
---MY CONTROLLER WITHOUT FORM VALIDATION---
public function update_nik_pindah_kelurahan($id_surat_pindah){
if ($this->form_validation->run() == FALSE){
$id_surat_pindah = $this->input->post('id_surat_pindah');
$id_surat = $this->input->post('id_surat');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null) {
$data = array(
'id_surat' => $id_surat,
'id_surat_pindah' => $id_surat_pindah
);
foreach ($a as $row){
$dataaa = [
'id_surat' => $id_surat_pindah,
'nik_pindah' =>$row,
];
$wheree = array(
'id_surat' => $id_surat_pindah
);
$this->db->where('id_surat', $id_surat_pindah);
$update = $this->db->update('nik_pindah', $dataaa);
if ($update) {
$i++;
}
}
$where = array(
'id_surat_pindah' => $id_surat_pindah
);
$this->m_pindah_kelurahan->update_data($where, $data, 'surat_pindah');
}
redirect('admin_pindah_kelurahan/index');
}
}
---MY VIEWS---
<?php
foreach ($nik_pindah_kelurahan as $np) :
if (empty($np->nik_pindah)) { ?>
<input type="text" name="nik_pindah" class="form-control" value="belum tersedia"><br>
<?php } else {?>
<input type="text" name="nik_pindah[]" class="form-control" value="<?php echo $np->nik_pindah ?>"><br>
<?php } endforeach; ?>
If with or without form validation will updating data but all column where id_surat is same (not particular value)
like this:
enter image description here then enter image description here
Everytime the foreach makes a loop, $this->db->where() has the same condition because $id_surat_pindah has always the same value, so you're updating the same rows once and once again. Also (if I understand it correctly), keep in mind that if $id_surat_pindah is not a unique key, everytime you make an UPDATE all the rows with its value will be affected.
Otherwise, I would recommend you to check your code using update_batch() instead the loop: https://www.codeigniter.com/userguide3/database/query_builder.html?highlight=update_batch
I was working on another person's code and when I deployed the laravel app the login page works but when I input the testing credentials it spits out this error
Trying to get property 'id' of non-object
in helpers.php line 159
at HandleExceptions->handleError(8, 'Trying to get property \'id\' of non-object', '/var/www/html/first-project/app/Helpers/helpers.php', 159, array('fields' => object(Collection), 'fieldsValues' => object(Collection), 'htmlFields' => array(), 'startSeparator' => '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">', 'endSeparator' => '</div>', 'field' => object(CustomField), 'dynamicVars' => array('$RANDOM_VARIABLE$' => 'var15931958241638660037ble', '$FIELD_NAME$' => 'phone', '$DISABLED$' => '', '$REQUIRED$' => '"required" => "required",', '$MODEL_NAME_SNAKE$' => 'user', '$FIELD_VALUE$' => '\'+136 226 5660\'', '$INPUT_ARR_SELECTED$' => '+136 226 5660'), 'gf' => object(GeneratorField), 'value' => object(CustomFieldValue)))
in helpers.php line 159
The actual function referred to is the following
function generateCustomField($fields, $fieldsValues = null)
{
$htmlFields = [];
$startSeparator = '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">';
$endSeparator = '</div>';
foreach ($fields as $field) {
$dynamicVars = [
'$RANDOM_VARIABLE$' => 'var' . time() . rand() . 'ble',
'$FIELD_NAME$' => $field->name,
'$DISABLED$' => $field->disabled === true ? '"disabled" => "disabled",' : '',
'$REQUIRED$' => $field->required === true ? '"required" => "required",' : '',
'$MODEL_NAME_SNAKE$' => getOnlyClassName($field->custom_field_model),
'$FIELD_VALUE$' => 'null',
'$INPUT_ARR_SELECTED$' => '[]',
];
$gf = new GeneratorField();
if ($fieldsValues) {
foreach ($fieldsValues as $value) {
if ($field->id === $value->customField->id) {
$dynamicVars['$INPUT_ARR_SELECTED$'] = $value->value ? $value->value : '[]';
$dynamicVars['$FIELD_VALUE$'] = '\'' . addslashes($value->value) . '\'';
$gf->validations[] = $value->value;
continue;
}
}
}
// dd($gf->validations);
$gf->htmlType = $field['type'];
$gf->htmlValues = $field['values'];
$gf->dbInput = '';
if ($field['type'] === 'selects') {
$gf->htmlType = 'select';
$gf->dbInput = 'hidden,mtm';
}
$fieldTemplate = HTMLFieldGenerator::generateCustomFieldHTML($gf, config('infyom.laravel_generator.templates', 'adminlte-templates'));
if (!empty($fieldTemplate)) {
foreach ($dynamicVars as $variable => $value) {
$fieldTemplate = str_replace($variable, $value, $fieldTemplate);
}
$htmlFields[] = $fieldTemplate;
}
// dd($fieldTemplate);
}
foreach ($htmlFields as $index => $field) {
if (round(count($htmlFields) / 2) == $index + 1) {
$htmlFields[$index] = $htmlFields[$index] . "\n" . $endSeparator . "\n" . $startSeparator;
}
}
$htmlFieldsString = implode("\n\n", $htmlFields);
$htmlFieldsString = $startSeparator . "\n" . $htmlFieldsString . "\n" . $endSeparator;
// dd($htmlFieldsString);
$renderedHtml = "";
try {
$renderedHtml = render(Blade::compileString($htmlFieldsString));
// dd($renderedHtml);
} catch (FatalThrowableError $e) {
}
return $renderedHtml;
}
its usage is as follows in the controllers. It is used many times in almost all controllers for example in the UserController.php file I think this is the calling method. I am not that well versed in laravel sorry for any noob mistakes in advance.
public function profile()
{
$user = $this->userRepository->findWithoutFail(auth()->id());
unset($user->password);
$customFields = false;
$role = $this->roleRepository->pluck('name', 'name');
$rolesSelected = $user->getRoleNames()->toArray();
$customFieldsValues = $user->customFieldsValues()->with('customField')->get();
$hasCustomField = in_array($this->userRepository->model(), setting('custom_field_models', []));
if ($hasCustomField) {
$customFields = $this->customFieldRepository->findByField('custom_field_model', $this->userRepository->model());
$customFields = generateCustomField($customFields, $customFieldsValues);
}
return view('settings.users.profile', compact(['user', 'role', 'rolesSelected', 'customFields', 'customFieldsValues']));
}
You have to change this line
From
$user = $this->userRepository->findWithoutFail(auth()->id());
To
$user = $this->userRepository->findWithoutFail(auth()->user()->id());
My first guess, change this $user = $this->userRepository->findWithoutFail(auth()->id()); to $user = $this->userRepository->findWithoutFail(auth()->user()->id);
Added auth()->user()->id;
View:
<select class="form-control" data-placeholder="Choose a Category" tabindex="1" name="venues[]" multiple >
<option value="">Select One</option>
<?php foreach($list_of_venues as $venues){ ?>
<option value="<?php echo $venues->activity_venue_id; ?>"><?php echo $venues->venue_title; ?></option>
<?php } ?>
</select>
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Create_activity_session extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('vendor_model');
$this->load->database();
}
public function index()
{
error_reporting(0);
$session_data = $this->session->userdata('logged_in');
$data['account_name'] = $session_data['account_name'];
if($session_data['account_name']){
$data['id'] = $session_data['id'];
$id = $data['id'];
$data['list_of_activities'] = $this->vendor_model->list_of_activities_by_vendor($id);
$data['list_of_venues'] = $this->vendor_model->list_of_venues_by_vendor($id);
$data['list_of_booking_fields'] = $this->vendor_model->list_of_booking_fields_by_vendor_by_venue($id);
$this->form_validation->set_rules('activity_title','Activity Title','required');
$this->form_validation->set_rules('venues[]','Selecting Venue','required');
$this->form_validation->set_rules('start_date','Start Date','required');
$this->form_validation->set_rules('end_date','End Date','required');
$this->form_validation->set_rules('start_time','Start Time','required');
$this->form_validation->set_rules('end_time','End Time','required');
$this->form_validation->set_rules('number_of_seats','Number of Bookings','required');
$this->form_validation->set_rules('price','Price','required');
if($this->form_validation->run()==FALSE){
$data['list_of_activities'] = $this->vendor_model->list_of_activities_by_vendor($id);
$data['list_of_venues'] = $this->vendor_model->list_of_venues_by_vendor($id);
$data['list_of_booking_fields'] = $this->vendor_model->list_of_booking_fields_by_vendor_by_venue($id);
$this->load->view('vendor/create_activity_session',$data);
} else {
$end_date = $this->input->post('end_date');
$start_date = $this->input->post('start_date');
if($end_date < $start_date){
$data['error'] = 'Start Date should not be greater than the End Date.';
$this->load->view('vendor/create_activity_session',$data);
} else {
$activity_id = $this->input->post('activity_title');
$venue_id = implode(',',$this->input->post('venues'));
$data = array(
'activity_by_id' => $this->input->post('activity_title'),
'venue_id' => $venue_id,
'start_date' => $this->input->post('start_date'),
'end_date' => $this->input->post('end_date'),
'start_time' => $this->input->post('start_time'),
'end_time' => $this->input->post('end_time'),
'number_of_seats' => $this->input->post('number_of_seats'),
'price' => $this->input->post('price'),
'vendor_id' => $id,
'status' => 1,
'created_on' => date('Y-m-d h:i:s')
);
$result = $this->vendor_model->create_activity_dates_time($data);
$session_id = $this->db->insert_id();
// $venues = $this->input->post('venues');
$data = array(
'venue_activity_id' => $venue_id,
);
$result2 = $this->vendor_model->update_activity($data,$activity_id);
$venues = $this->input->post('venues');
$venue_count = count($venues);
for($i = 0;$i<=$venue_count; $i++){
$data = array(
'session_by_id' => $session_id,
'venue_by_id' => $venues[$i]
);
$result3 = $this->vendor_model->create_venues_by_session($data);
}
$data['success'] = 'You have created the new Activity Session';
$data['list_of_activities'] = $this->vendor_model->list_of_activities_by_vendor($id);
$data['list_of_venues'] = $this->vendor_model->list_of_venues_by_vendor($id);
$data['list_of_booking_fields'] = $this->vendor_model->list_of_booking_fields_by_vendor_by_venue($id);
$this->load->view('vendor/create_activity_session',$data);
}
}
} else {
redirect('http://localhost/bookleisure/vendor/login');
}
}
}
I have an issue with inserting the multiple dropdown values that shows the database error
venue_by_id cannot be null.
I wanted to insert the multiple dropdown rows.
try replacing
for($i = 0;$i<=$venue_count; $i++){
with
for($i = 0;$i<$venue_count; $i++){
Don't forget that array indexes start with 0 so last item in array is always count($array) - 1
I have these following functions.
public function importExcelFile(){
$file = $_FILES['file']['tmp_name'];
$data = extract_excel_data($file);
$i = 0;
foreach($data['values'] as $dataValues) {
$categories = [];
$brands = [];
$models = [];
foreach($dataValues as $value){
if(array_filter($value)) {
/* If a row does not contain brand/category/model for the product then fetch the resp. info. from previous row */
if(empty(trim($value[0]))) {
$categories[] = $prev_cat;
} else {
$categories[] = strtoupper(trim($value[0]));
$prev_cat = strtoupper(trim($value[0]));
}
if(empty(trim($value[1]))) {
$brands[] = $prev_brand;
} else {
$brands[] = strtoupper(trim($value[1]));
$prev_brand = strtoupper(trim($value[1]));
}
if(empty(trim($value[2]))) {
$models[] = $prev_model;
} else {
$models[] = $value[2];
$prev_model = $value[2];
}
}
}
//insert device category
$this->insert_setups('category', $categories);
//insert brand
$this->insert_setups('brand', $brands);
// Check if branch already exists in the database
$check_branch = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->result();
$branch_arr = [];
//insert branch
if(empty($check_branch)) {
$branch_arr = array(
'name' => $data['branch'][$i].' branch',
'location' => $data['branch'][$i],
'status' => 1,
'created_by' => $this->session->userdata('id'),
'created_on' => date('Y-m-d')
);
$this->global_model->insertData('branch', $branch_arr);
}
$branch_id = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->row()->id;
$db_device_categories = [];
$db_brands = [];
// get categoris, brands
$db_device_categories = $this->arrangeArray('category', $where =array());
$db_brands = $this->arrangeArray('brand', $where =array());
//detail_print($db_brands);
// insert new models from database
foreach(array_unique($models) as $model_key=>$model){
$check_model = $this->global_model->getDetailByWhere('model', array('name'=>$model))->result();
$insert = [];
if(empty($check_model)){
$insert = array(
'name' => $model,
'item_type' => 1,
'category_id' => $db_device_categories[$categories[$model_key]],
'brand_id' => $db_brands[$brands[$model_key]],
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData('model', $insert);
}
}
$db_device_models = [];
// get models from database
$db_device_models = $this->arrangeArray('model', $where = array('item_type'=>1));
$categoriy_id = [];
$brand_id = [];
$model_id = [];
$opening_stock = [];
// arrange the exported array with respective id
foreach($dataValues as $values){
if(array_filter($values)) {
if(empty(trim($values[0]))) {
$category_id = $prev_cat;
} else {
$category_id = strtoupper(trim($values[0]));
$prev_cat = strtoupper(trim($values[0]));
}
if(empty(trim($values[1]))) {
$brand_id = $prev_brand;
} else {
$brand_id = strtoupper(trim($values[1]));
$prev_brand = strtoupper(trim($values[1]));
}
if(empty(trim($values[2]))) {
$model_id = $prev_model;
} else {
$model_id = $values[2];
$prev_model = $values[2];
}
$opening_stock[] = array(
'category_id' => $db_device_categories[$category_id],
'brand_id' => $db_brands[$brand_id],
'model_id' => $db_device_models[$model_id],
'imei' => (string)$values[3],
'cost_price' => isset($values[5]) ? $values[5] : 0,
'selling_price' => isset($values[6]) ? $values[6] : 0
);
}
}
$group_by_model = [];
// group the array by model_id
foreach(array_unique($models) as $model1){
$where = $db_device_models[$model1];
$group_by_model[] = array_filter($opening_stock, function($elements) use ($where){
return $elements["model_id"] == $where;
});
}
if(!$this->purchase_model->insertOpeningStock($group_by_model, $branch_id)){
$this->session->set_flashdata('error', 'Opening stock of devices insertion failed.');
redirect('purchase/uploadExcelFile');
}
$i++;
}
$this->session->set_flashdata('success', 'Opening stock of devices added successfully.');
redirect('purchase/uploadExcelFile');
}
private function arrangeArray($table, $where){
$list = $this->global_model->getDetailByWhere($table, $where)->result_array();
foreach($list as $item){
$name = $item['name'];
$arranged_list[$name] = $item['id'];
}
return !empty($arranged_list) ? $arranged_list : NULL;
}
private function insert_setups($table_name, $setups){
foreach(array_unique($setups) as $value){
$check_setup = $this->global_model->getDetailByWhere($table_name, array('name'=>$value))->result();
if(empty($check_setup)){
$insert = array(
'name' => $value,
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData($table_name, $insert);
}
}
}
What this function does is, it extracts data from the uploaded excel file and inserts the data to various tables accordingly. Now as you can see, there are multiple queries running in different locations inside the importExcelFile() method. So my question is, how do I use codeigniter transaction in such a way that all the queries inside this function are performed atomically. If any one query fails, all other query's work is rolled back. Also, is this code considered clean ?
P.S. I'm so sorry if my last question was inappropriate here.
this might be helpful to you.
transactions in codeigniter
$this->db->trans_begin();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
I have a script for inserting a product custom options in Magento. Its working fine for single custom option, if there are multiple custom options for a single product then it insert only single custom option and discard others.
<?php
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
// Include Magento application
require_once ( "../app/Mage.php" );
umask(0);
// Initialize Magento
Mage::app("default");
$start = 0;
$totalno =1000;
$row = 0;
$sku = 0;
$baseRowoption = array();
$myarrayoption = array();
if (($handle = fopen("custom_option-final.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle,",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
if($row == 0){
$baseRowoption[$c]=$data[$c];
}else{
if($c==0){
$sku=$data[$c];
}
$myarrayoption[$sku][$row][$baseRowoption[$c]]=$data[$c];
}
}
$row++;
if($row > $totalno){
break;
}
}
fclose($handle);
}
$myarrayoptionfinal = array();
foreach($myarrayoption as $key=>$myarrayoption1){
//if($key != "smartek-rx3044"){ break; }
foreach($myarrayoption1 as $myarrayoption11){
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['input_type'] = $myarrayoption11['input_type'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['required'] = $myarrayoption11['required'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['sort_order'] = $myarrayoption11['sort_order'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_title'][] = $myarrayoption11['row_title'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_price'][] = $myarrayoption11['row_price'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_price_type'][] = $myarrayoption11['row_price_type'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_sku'][] = $myarrayoption11['row_sku'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_sort_order'][] = $myarrayoption11['row_sort_order'];
}
}
echo "<pre>";
echo "total No : ".count($myarrayoptionfinal);
echo "<br />";
//print_r($myarrayoptionfinal);
$i=0;
foreach($myarrayoptionfinal as $keys=>$myarrayoptionfinal1){
if($i<$start){
$i++; continue;
}
echo "<br />".$i."--->";
$i++;
echo $keys."--->";
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$keys);
if($product){
foreach ($product->getProductOptionsCollection() as $option)
{
$optionsData = $option->getData();
$optionsData['is_delete'] = 1;
$product->setProductOptions(array($option->getId() => $optionsData));
$product->setCanSaveCustomOptions(true);
$product->save();
}}else{
continue;
}
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$keys);
print_r($product->getData("entity_id"));
foreach($myarrayoptionfinal1 as $keysub=>$myarrayoptionfinal11){
$subarray = array();
foreach($myarrayoptionfinal11['row_title'] as $keysub1=>$myarrayoptionfinal111){
$subarray[]=array(
'is_delete' => 0,
'title' => $myarrayoptionfinal111,
'price_type' => $myarrayoptionfinal11['row_price_type'][$keysub1],
'price' => $myarrayoptionfinal11['row_price'][$keysub1],
'sku' => $keys.'_'.$myarrayoptionfinal11['row_sku'][$keysub1],
'sort_order' => $myarrayoptionfinal11['row_sort_order'][$keysub1],
'option_type_id'=> -1,
);
}
$required = false;
if($myarrayoptionfinal11["required"] == 1) $required = true;
$opt = array(
'is_delete' => 0,
'is_require' => $required,
'previous_group' => '',
'title' => $keysub,
'type' => $myarrayoptionfinal11["input_type"],
'price_type' => '',
'price' => '',
'sort_order' => $myarrayoptionfinal11["sort_order"],
/** array of values for this option **/
'values' => $subarray,
);
}
try {
//print_r($opt);
$option = Mage::getModel('catalog/product_option')
->setProduct($product)
->addOption($opt)
->saveOptions();
$product->setHasOptions(1);
$product->save();
}
catch (Exception $e) {
echo 'Caught exception 2: '.$e->getMessage()."\n";
continue;
}
}
Add custom option to multiple products is quite difficult because there are multiple type custom option in magento like (dropdown, text etc.) also you will found in each custom option multiple values which you need to handle.
http://www.magentocommerce.com/magento-connect/custom-option-manger.html
This extension provides exact functionality multiple custom options for multiple products.