Error adding Custom Option in magento - magento

I have this error "Fatal error: Uncaught exception 'Mage_Eav_Model_Entity_Attribute_Exception' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '6152-0-11-0' for key"
Whe add custom optión programatically in magento, i use this function:
function createCustomOption($value, $customoptions_price, $sku, $title, $type, $noOption = false)
{
$custom_options = array();
if ($type && $value != "" && $value) {
$values = explode(',', $value);
$skus = explode(',', $sku);
$is_required = 1;
$customoptions_prices = explode(',', $customoptions_price);
if (count($values)) {
/**If the custom option has options*/
if (! $noOption) {
$is_required = 1;
$sort_order = 0;
$custom_options[ ] = array(
'is_delete' => 0,
'title' => $title,
'previous_group' => "",
'previous_type' => "",
'type' => $type,
'is_require' => $is_required,
'sort_order' => $sort_order ,
'values' => array()
);
for($i = 0; $i < (count($values)) ; $i++)
{
switch ($type) {
case 'drop_down':
case 'radio':
case 'checkbox':
case 'multiple':
default:
$custom_options[count($custom_options)-1]['values'][ ] = array(
'is_delete' => 0,
'title' => $values[$i],
'option_type_id' => –1,
'price_type' => 'fixed',
'price' => $customoptions_prices[$i],
'sku' => $skus[$i],
'sort_order' => $i);
break;
}
}
return $custom_options;
}
/**If the custom option doesn't have options | Case: area and field*/
else {
$is_required = 1;
$sort_order = 0;
$custom_options[ ] = array(
"is_delete" => 0,
"title" => $title,
"previous_group" => "text",
"price_type" => 'fixed',
"price" => "0",
"type" => $type,
"is_required" => $is_required
);
return $custom_options;
}
}
}
return false;
}
I call it from here:
$product = Mage::getModel('catalog/product')->load(6152);
unset($optionData);
$precio = 100;
$custom_title = "Unidad,Caja de 10 unidades";
$customoptions_price = "0,".$precio."";
$prod_sku = "unidadesku,cajasku";
$customoption_main_title = "Seleccione unidades o cajas";
$option_type = "drop_down";
$optionData[ ] = createCustomOption($custom_title, $customoptions_price, $prod_sku, $customoption_main_title, $option_type);
if(count($product->getOptions()) == 0){
foreach ($optionData as $options) {
foreach ($options as $option) {
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option);
$opt->saveOptions();
}
}
$product->setHasOptions(1)->save();

I solved it adding in my script this line:
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

Related

Data is not inserted into database using codeigniter

I have a form where user insert their basic details and after submitting form it will redirect on view page. I trying to submit it redirect on view page without inserting data into database. I debug my code of controller I come to know that $request = $this->getRequest(); code in $request I am getting GET [ 1 ] and post is empty and in if condition here used $this->getRequest()->isPost() to check whether that post is true or false. Please find screenshot of code of controller.
Controller function
public function addAction() {
$captcha = new Zend_Session_Namespace('captcha');
$captcha->captcha = session_id();
$request = $this->getRequest();
if ($this->getRequest()->isPost()) {
if ($form->isValidPartial($request->getPost())) {
$dataform = $request->getPost();
$alphabet =
"abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$randomPassword = implode($pass); //turn the array into a string
$dataform['password'] = $randomPassword;
if ($dataform['vercode'] != $_SESSION["vercode"]) {
$msg = "Please enter a correct code!";
$this->view->assign('errorMessage', $msg);
return FALSE;
}
if ($dataform['sessionCheck'] != $captcha->captcha) {
$this->view->assign('errorMessage', CSRF_ATTACK);
return FALSE;
}
if($dataform['name'] == 2 && $dataform['statename'] == 0){
$this->view->assign('errorMessage', 'Please select state
for the state officials!');
return;
}
$Contactusobj = new Application_Model_User;
$countdata = $Contactusobj-
>checkuserclient($dataform['username']);
$countemail = $Contactusobj-
>checkemail($dataform['email']);
if(($countdata == 0)){
$match = $Contactusobj->insertuserdetails($dataform);
$description = 'Add New User </br>';
if($dataform[name] && $dataform[name] != 0){
$rolename = $Contactusobj-
>getuserrolename($dataform[name]);
$description .= '<span>Role:
</span>'.$rolename.'</br>';
}
if($dataform[ministry_name] && $dataform[ministry_name]
!= 0){
$ministryname = $Contactusobj-
>Getministryname($dataform[ministry_name]);
$description .= '<span>Ministry:
</span>'.$ministryname .'</br>';
}
if($dataform[statename] && $dataform[statename] != 0){
$statename = $Contactusobj-
>getuserstatename($dataform[statename]);
$description .= '<span>State:
</span>'.$statename.'</br>';
}
if($dataform[cityname] && $dataform[cityname] != 0){
$cityname = $Contactusobj-
>getdistrictname($dataform[cityname]);
$description .= '<span>City:
</span>'.$cityname.'</br>';
}
$description .= '<span>User Name:
</span>'.$dataform[username].'</br>';
$description .= '<span>First Name:
</span>'.$dataform[firstname].'</br>';
$description .= '<span>Last Name:
</span>'.$dataform[lastname].'</br>';
$description .= '<span>Email:
</span>'.$dataform[email].'</br>';
$description .= '<span>Mobile:</span>'.$dataform[mobile];
$auditlog = array("uid" => $userid->userid,
"application_type" => 'User',
"description" => $description
);
$auditobj = new Application_Model_Auditlog;
$auditobj->insertauditlog($auditlog);
/***************audit log end by braj***************/
$mailObj = new Zend_Mail();
$username = $dataform['username'];
$fname = ucfirst($dataform['firstname']);
$weblink = WEB_LINK;
$body = MESSAGE_BODY;
$body = str_replace('{user_name}',$username,$body);
$body = str_replace('{fname}',$fname,$body);
$body =
str_replace('{user_password}',$dataform['password'],$body);
$body = str_replace('{web_link}',$weblink,$body);
$subject= MAIL_SUBJECT;
$to =$dataform['email'];
$from =MAIL_FROM;
$name = MAIL_NAME;
$mailObj->setSubject($subject);
$mailObj->setBodyHtml($body);
$mailObj->addTo($to, $name);
$mailObj->setFrom($from,
$name);//print_r($mailObj);die();
$mailObj->send();
$this->_redirect('/user/add?actmsg=add');
}else{
if($countdata){
$this->view->assign('errorMessage', 'Your
username is already exists in the database.');
return;
} }}}}}}}
Model User.php
public function insertuserdetails($dataform) {
$userid = new Zend_Session_Namespace('userid');
$user_table = new Zend_Db_Table('dbt_users');
$date = date("Y-m-d H:i:s");
$datainsert = "";
$datainsert = array(
'state' => $dataform['statename'],
//'cityname'=> $dataform['cityname'],
'ministry_name' => $dataform['ministry_name'],
'username' => $dataform['username'],
'password' => hash_hmac('sha256', $dataform['password'], ''),
'firstname' => $dataform['firstname'],
'lastname' => $dataform['lastname'],
'organisation' => '',
'mobile' => $dataform['mobile'],
'email' => $dataform['email'],
'telephone' => '',
'address' => '',
'role' => $dataform['name'],
'upload' => '',
'dateAdded' => $date,
'dateModify' => $date,
'status' => 1,
'created_by' => $userid->userid,
'login_time' => 1,
'tmp_password' => md5(uniqid(rand(), TRUE)) . substr(md5($dataform['username']), 2, 10),
'reset_time' => $date
);
$insertdata = $user_table->insert($datainsert);
return $insertdata; }

"An illegal choice is detected..." error with dynamic dropdown select list I Drupal8

I wrote this code for dynamic dropdown select list in hook_form_alter. Options are populated by an external DB.
function car2db_annuncio_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_annuncio_form') {
$options_type = car2db_annuncio_type_dropdown_options();
$form['field_marca']['#prefix'] = '<div id="field_marca">';
$form['field_marca']['#suffix'] = '</div>';
$form['field_tipologia']['widget']['#options'] = $options_type;
$form['field_tipologia']['widget']['#ajax'] = array(
'event' => 'change',
'callback' => 'car2db_annuncio_make_ajax_callback',
'wrapper' => 'field_marca',
'disable-refocus' => FALSE,
'progress' => [
'type' => 'throbber',
'message' => t('Verify...'),
]
);
}
}
function car2db_annuncio_type_dropdown_options() {
$connection = Database::getConnection('default', 'migrate');
$dropdown_type = ['none' => '- Seleziona - '];
$sql_type = "SELECT * FROM `car_type`";
$query_type = $connection->query($sql_type);
$res_type = $query_type->fetchAll();
foreach ($res_type as $row){
$key = $row->id_car_type;
$value = $row->name;
$dropdown_type[$key] = $value;
}
return $dropdown_type;
}
function car2db_annuncio_make_dropdown_options($key_type) {
$connection = Database::getConnection('default', 'migrate');
$dropdown_make = ['none' => '- Seleziona - '];
$sql_make = "SELECT * FROM `car_make` WHERE `id_car_type` = :tipo";
$query_make = $connection->query($sql_make, [':tipo' => $key_type]);
$res_make = $query_make->fetchAll();
foreach ($res_make as $row){
$Key_make = $row->id_car_make;
$Make_value = $row->name;
$dropdown_make[$Key_make] = $Make_value;
}
return $dropdown_make;
}
function car2db_annuncio_make_ajax_callback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('field_tipologia')) {
$selectedValue = (int) $selectedValue[0]['value'] ? (int) $selectedValue[0]['value'] : 0;
$options_marca = car2db_annuncio_make_dropdown_options($selectedValue);
$form['field_marca']['widget']['#options'] = $options_marca;
}
return $form['field_marca'];
}
Now, when click on "Save button", there is always "An illegal choice is detected...." error.
I also tried loading options into the hook_form alter, but it always returns an error.
Where am i wrong?
I remember this confusing the hell out of me back in the day when I first started playing with ajax forms in Drupal.
Hopefully I am remembering this correctly.
Basically, you have to move your logic for adding the dynamic options into the form build function (but in your case, it's the alter function).
When the ajax function is called, the form is still rebuilt and your alter function is called (and has the current form_state).
Your ajax function will just return the new form element.
Something like below (untested)
function car2db_annuncio_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_annuncio_form') {
$options_type = car2db_annuncio_type_dropdown_options();
$form['field_marca']['#prefix'] = '<div id="field_marca">';
$form['field_marca']['#suffix'] = '</div>';
$form['field_tipologia']['widget']['#options'] = $options_type;
$form['field_tipologia']['widget']['#ajax'] = array(
'event' => 'change',
'callback' => 'car2db_annuncio_make_ajax_callback',
'wrapper' => 'field_marca',
'disable-refocus' => FALSE,
'progress' => [
'type' => 'throbber',
'message' => t('Verify...'),
]
);
// Check selected value here.
if ($selectedValue = $form_state->getValue('field_tipologia')) {
$selectedValue = (int) $selectedValue[0]['value'] ? (int) $selectedValue[0]['value'] : 0;
$options_marca = car2db_annuncio_make_dropdown_options($selectedValue);
$form['field_marca']['widget']['#options'] = $options_marca;
}
}
}
function car2db_annuncio_type_dropdown_options() {
$connection = Database::getConnection('default', 'migrate');
$dropdown_type = ['none' => '- Seleziona - '];
$sql_type = "SELECT * FROM `car_type`";
$query_type = $connection->query($sql_type);
$res_type = $query_type->fetchAll();
foreach ($res_type as $row){
$key = $row->id_car_type;
$value = $row->name;
$dropdown_type[$key] = $value;
}
return $dropdown_type;
}
function car2db_annuncio_make_dropdown_options($key_type) {
$connection = Database::getConnection('default', 'migrate');
$dropdown_make = ['none' => '- Seleziona - '];
$sql_make = "SELECT * FROM `car_make` WHERE `id_car_type` = :tipo";
$query_make = $connection->query($sql_make, [':tipo' => $key_type]);
$res_make = $query_make->fetchAll();
foreach ($res_make as $row){
$Key_make = $row->id_car_make;
$Make_value = $row->name;
$dropdown_make[$Key_make] = $Make_value;
}
return $dropdown_make;
}
function car2db_annuncio_make_ajax_callback(array &$form, FormStateInterface $form_state) {
// Just return the form element (that has been rebuilt in the form_alter)
return $form['field_marca'];
}

Laravel Sms Configuration

We using to private message service. I want send sms notification to message received person.
I searched but couldn't find. But I could do this much maybe wrong maybe right.
Sometimes the page gave a complete data error
I Understand may have given the recipient wrong
I do this code ;
if(config('config.task_sms_notification')){
$message = 'Merhaba, Suit 13\'de Tarafiniza Yeni Mesaj Gonderildi. Gonderen: '.$request->input('to_user_id');
$user = $new_message->to_user_id;
if($user->Profile->mobile)
$user->notify(new TaskNotification($message,$task));
}
}
Private message service codes;
public function __construct()
{
$this->middleware('feature_available:enable_message');
}
public function validateLiveMessage($type,$value){
$message = Message::where($type,'=',$value)->where(function($query) {
$query->where(function($query1){
$query1->where('from_user_id','=',\Auth::user()->id)
->where('delete_sender','=','0');
})->orWhere(function($query2){
$query2->where('to_user_id','=',\Auth::user()->id)
->where('delete_receiver','=','0');
});
})->first();
return ($message) ? : 0;
}
public function validateDeleteMessage($type,$value){
$message = Message::where($type,'=',$value)->where(function($query) {
$query->where(function($query1){
$query1->where('from_user_id','=',\Auth::user()->id)
->where('delete_sender','=','1');
})->orWhere(function($query2){
$query2->where('to_user_id','=',\Auth::user()->id)
->where('delete_receiver','=','1');
});
})->first();
return ($message) ? : 0;
}
public function index(){
$table_data['inbox-table'] = array(
'source' => 'message/inbox',
'title' => 'Inbox',
'id' => 'inbox_table',
'data' => array(
trans('messages.option'),
trans('messages.from'),
trans('messages.subject'),
trans('messages.date_time'),
''
)
);
$table_data['sent-table'] = array(
'source' => 'message/sent',
'title' => 'Sent',
'id' => 'sent_table',
'data' => array(
trans('messages.option'),
trans('messages.to'),
trans('messages.subject'),
trans('messages.date_time'),
''
)
);
$table_data['starred-table'] = array(
'source' => 'message/starred',
'title' => 'Starred',
'id' => 'starred_table',
'data' => array(
trans('messages.option'),
'',
trans('messages.subject'),
trans('messages.date_time'),
''
)
);
$table_data['trash-table'] = array(
'source' => 'message/trash',
'title' => 'Trash',
'id' => 'trash_table',
'data' => array(
trans('messages.option'),
'',
trans('messages.subject'),
trans('messages.date_time'),
''
)
);
$users = \App\User::where('id','!=',\Auth::user()->id)->get()->pluck('full_name','id')->all();
$messages = Message::whereToUserId(\Auth::user()->id)
->whereDeleteReceiver('0')->whereNull('reply_id')
->get();
$count_inbox = count($messages);
$assets = ['summernote','datatable'];
$menu = 'message';
return view('message.index',compact('users','count_inbox','assets','menu','table_data'));
}
public function starred(Request $request){
$message = $this->validateLiveMessage('token',$request->input('token'));
if(!$message)
return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']);
if(\Auth::user()->id == $message->from_user_id)
$message->is_starred_sender = ($message->is_starred_sender) ? 0 : 1;
else
$message->is_starred_receiver = ($message->is_starred_receiver) ? 0 : 1;
$message->save();
return response()->json(['status' => 'success']);
}
public function lists($type,Request $request){
if($type == 'inbox')
$inbox_message = Message::whereToUserId(\Auth::user()->id)
->select(\DB::raw('reply_id'))
->whereDeleteReceiver(0)
->whereNotNull('reply_id')
->groupBy('reply_id')
->get()
->pluck('reply_id')
->all();
elseif($type == 'sent')
$sent_message = Message::whereFromUserId(\Auth::user()->id)
->select(\DB::raw('reply_id'))
->whereDeleteSender(0)
->whereNotNull('reply_id')
->groupBy('reply_id')
->get()
->pluck('reply_id')
->all();
if($type == 'sent')
$messages = Message::where(function($query) use($sent_message){
$query->where(function($query1) use($sent_message){
$query1->where('from_user_id','=',\Auth::user()->id)
->where('delete_sender','=','0')
->whereNull('reply_id');
})->orWhereIn('id',$sent_message);
})->orderBy('created_at','desc')->get();
elseif($type == 'inbox')
$messages = Message::where(function($query) use($inbox_message){
$query->where(function($query1) use($inbox_message){
$query1->where('to_user_id','=',\Auth::user()->id)
->where('delete_receiver','=','0')
->whereNull('reply_id');
})->orWhereIn('id',$inbox_message);
})->orderBy('created_at','desc')->get();
elseif($type == 'starred')
$messages = Message::where(function($query){
$query->where(function($query1){
$query1->where('from_user_id','=',\Auth::user()->id)
->where('delete_sender','=',0)
->where('is_starred_sender','=',1);
})->orWhere(function($query2){
$query2->where('to_user_id','=',\Auth::user()->id)
->where('delete_receiver','=',0)
->where('is_starred_receiver','=',1);
});
})->orderBy('created_at','desc')->get();
elseif($type == 'trash')
$messages = Message::where(function($query){
$query->where(function($query1){
$query1->where('from_user_id','=',\Auth::user()->id)
->where('delete_sender','=',1);
})->orWhere(function($query2){
$query2->where('to_user_id','=',\Auth::user()->id)
->where('delete_receiver','=',1);
});
})->orderBy('created_at','desc')->get();
$rows=array();
foreach($messages as $message){
$starred = 0;
if(\Auth::user()->id == $message->from_user_id)
$starred = ($message->is_starred_sender) ? 1 : 0;
else
$starred = ($message->is_starred_receiver) ? 1 : 0;
$option = (($type != 'trash') ? '<div class="btn-group btn-group-xs"> <i class="fa fa-arrow-circle-right"></i>' : '').
(($type != 'trash') ? ' <i class="fa fa-'.($starred ? 'star starred' : 'star-o').'"></i>' : '').
(($type == 'trash') ? ' <i class="fa fa-retweet" data-toggle="tooltip" data-title="'.trans('messages.restore').'"></i>' : '').
(($type != 'trash') ? delete_form(['message.trash',$message->id]) : delete_form(['message.destroy',$message->id])).'</div>';
$source = (\Auth::user()->id == $message->from_user_id) ? $message->UserTo->full_name : $message->UserFrom->full_name;
if($type == 'starred' || $type == 'trash')
$source .= (\Auth::user()->id == $message->from_user_id) ? ' <span class="label label-success">Sent</span>' : ' <span class="label label-info">Inbox</span>';
$unread = 0;
if($type == 'inbox' && ((!$message->is_read && $message->to_user_id == \Auth::user()->id) || ($message->Replies->where('to_user_id','=',\Auth::user()->id)->where('is_read','=',0)->count())))
$unread = 1;
if($message->Replies->count() && ($type == 'inbox' || $type == 'sent'))
$source .= ' ('.(($message->Replies->where('to_user_id','=',\Auth::user()->id)->where('delete_receiver','=',0)->count())+($message->Replies->where('from_user_id','=',\Auth::user()->id)->where('delete_sender','=',0)->count())+1).')';
if($type == 'trash' && $message->reply_id != null && (($message->Reply->to_user_id == \Auth::user()->id && $message->Reply->delete_receiver == 1) || ($message->Reply->from_user_id == \Auth::user()->id && $message->Reply->delete_sender == 1)))
$show = 0;
else
$show = 1;
if($show)
$rows[] = array('<div class="btn-group btn-group-xs">'.$option.'</div>',
($unread) ? ('<strong>'.$source.'</strong>') : $source,
($unread) ? ('<strong>'.$message->subject.'</strong>') : $message->subject,
($unread) ? ('<strong>'.showDateTime($message->created_at).'</strong>') : showDateTime($message->created_at),
($message->attachments) ? '<i class="fa fa-paperclip"></i>' : ''
);
}
$list['aaData'] = $rows;
return json_encode($list);
}
public function forward($token){
$message = $this->validateLiveMessage('token',$token);
if(!$message)
return view('global.error',['message' => trans('messages.permission_denied')]);
\App\Upload::whereModule('message')->whereModuleId($message->id)->whereStatus(1)->update(['is_temp_delete' => 0]);
$uploads = \App\Upload::whereModule('message')->whereModuleId($message->id)->whereStatus(1)->get();
$users = \App\User::where('id','!=',\Auth::user()->id)->get()->pluck('full_name','id')->all();
return view('message.forward',compact('message','users','uploads'));
}
public function postForward(Request $request, $token){
$message = $this->validateLiveMessage('token',$token);
if(!$message)
return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']);
$validation = Validator::make($request->all(),[
'to_user_id' => 'required',
'subject' => 'required'
]);
$friendly_name = array('to_user_id' => 'receiver');
$validation->setAttributeNames($friendly_name);
if($validation->fails())
return response()->json(['message' => $validation->messages()->first(), 'status' => 'error']);
$existing_upload = \App\Upload::whereModule('message')->whereModuleId($message->id)->whereIsTempDelete(0)->count();
$new_upload_count = 0;
foreach($request->input('upload_key') as $upload_key)
$new_upload_count += \App\Upload::whereModule('message')->whereUploadKey($upload_key)->count();
if($existing_upload + $new_upload_count > config('constant.max_file_allowed.message'))
return response()->json(['message' => trans('messages.max_file_allowed',['attribute' => config('constant.max_file_allowed.message')]),'status' => 'error']);
$new_message = new Message;
$new_message->subject = $request->input('subject');
$new_message->body = clean($request->input('body'),'custom');
$new_message->attachments = $message->attachments;
$new_message->to_user_id = $request->input('to_user_id');
$new_message->from_user_id = \Auth::user()->id;
$new_message->token = randomString(30);
$new_message->attachments = ($existing_upload + $new_upload_count) ? 1 : 0;
$new_message->save();
$existing_uploads = \App\Upload::whereModule('message')->whereModuleId($message->id)->whereStatus(1)->whereIsTempDelete(0)->get();
foreach($existing_uploads as $existing_upload){
$new_upload_key = randomString(40);
$new_upload = new \App\Upload;
$new_upload->user_id = \Auth::user()->id;
$new_upload->module = 'message';
$new_upload->user_filename = $existing_upload->user_filename;
$upload_attachment = explode('.',$existing_upload->attachments);
$new_upload->attachments = str_random(50).'.'.$upload_attachment[1];
$new_upload->module_id = $new_message->id;
$new_upload->upload_key = $new_upload_key;
$new_upload->status = 1;
$new_upload->save();
\Storage::copy('attachments/'.$existing_upload->attachments, 'attachments/'.$new_upload->attachments);
}
foreach($request->input('upload_key') as $upload_key){
$uploads = \App\Upload::whereModule('message')->whereUploadKey($upload_key)->get();
$new_upload_key = randomString(40);
foreach($uploads as $upload){
$upload->module_id = $new_message->id;
$upload->status = 1;
$upload->save();
\Storage::move('temp_attachments/'.$upload->attachments, 'attachments/'.$upload->attachments);
}
}
\App\Upload::whereModule('message')->whereModuleId($message->id)->whereStatus(1)->whereIsTempDelete(1)->update(['is_temp_delete' => 0]);
$this->logActivity(['module' => 'message','module_id' => $new_message->id,'activity' => 'forwarded']);
return response()->json(['message' => trans('messages.message').' '.trans('messages.sent'), 'status' => 'success']);
}
public function load(Request $request){
$message = $this->validateLiveMessage('token',$request->input('token'));
if($message){
$replies = Message::where('reply_id','=',$message->id)->where(function($query){
$query->where(function($query1){
$query1->where('to_user_id','=',\Auth::user()->id)->where('delete_receiver','=','0');
})->orWhere(function($query2){
$query2->where('from_user_id','=',\Auth::user()->id)->where('delete_sender','=','0');
});
})->get();
return view('message.load',compact('message','replies'))->render();
}
}
public function reply($id,Request $request){
$message = $this->validateLiveMessage('id',$id);
if(!$message)
return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']);
$file_uploaded_count = \App\Upload::whereIn('upload_key',$request->input('upload_key'))->count();
if($file_uploaded_count > config('constant.max_file_allowed.message'))
return response()->json(['message' => trans('messages.max_file_allowed',['attribute' => config('constant.max_file_allowed.message')]),'status' => 'error']);
$data = $request->all();
$reply = new Message;
$reply->fill($data);
$reply->token = randomString(30);
$reply->subject = 'Re: '.$message->subject;
$reply->body = clean($request->input('body'),'custom');
$reply->from_user_id = \Auth::user()->id;
$reply->reply_id = $message->id;
$reply->attachments = ($file_uploaded_count) ? 1 : 0;
$reply->is_read = 0;
$reply->to_user_id = ($message->from_user_id == \Auth::user()->id) ? $message->to_user_id : $message->from_user_id;
$reply->save();
foreach($request->input('upload_key') as $upload_key){
$uploads = \App\Upload::whereModule('message')->whereUploadKey($upload_key)->get();
foreach($uploads as $upload){
$upload->module_id = $reply->id;
$upload->status = 1;
$upload->save();
\Storage::move('temp_attachments/'.$upload->attachments, 'attachments/'.$upload->attachments);
}
}
$this->logActivity(['module' => 'message','module_id' => $reply->id,'activity' => 'replied']);
return response()->json(['message' => trans('messages.message').' '.trans('messages.sent'), 'status' => 'success']);
}
public function store(MessageRequest $request){
$file_uploaded_count = \App\Upload::whereIn('upload_key',$request->input('upload_key'))->count();
if($file_uploaded_count > config('constant.max_file_allowed.message'))
return response()->json(['message' => trans('messages.max_file_allowed',['attribute' => config('constant.max_file_allowed.message')]),'status' => 'error']);
$data = $request->all();
$message = new Message;
$message->fill($data);
$message->token = randomString(30);
$message->body = clean($request->input('body'),'custom');
$message->from_user_id = \Auth::user()->id;
$message->is_read = 0;
$message->attachments = ($file_uploaded_count) ? 1 : 0;
$message->save();
foreach($request->input('upload_key') as $upload_key){
$uploads = \App\Upload::whereModule('message')->whereUploadKey($upload_key)->get();
foreach($uploads as $upload){
$upload->module_id = $message->id;
$upload->status = 1;
$upload->save();
\Storage::move('temp_attachments/'.$upload->attachments, 'attachments/'.$upload->attachments);
}
}
$this->logActivity(['module' => 'message','module_id' => $message->id,'activity' => 'sent']);
return response()->json(['message' => trans('messages.message').' '.trans('messages.sent'), 'status' => 'success']);
}
public function download($file){
$upload = \App\Upload::whereAttachments($file)->whereModule('message')->whereStatus(1)->first();
if(!$upload)
return redirect('/message')->withErrors(trans('messages.invalid_link'));
$message = Message::find($upload->module_id);
if(!$message)
return redirect('/message')->withErrors(trans('messages.invalid_link'));
if($message->to_user_id != \Auth::user()->id && $message->from_user_id != \Auth::user()->id)
return redirect('/message')->withErrors(trans('messages.permission_denied'));
if(!\Storage::exists('attachments/'.$upload->attachments))
return redirect('/message')->withErrors(trans('messages.file_not_found'));
$download_path = storage_path().config('constant.storage_root').'attachments/'.$upload->attachments;
return response()->download($download_path, $upload->user_filename);
}
public function view($token){
$message = $this->validateLiveMessage('token',$token);
if(!$message)
return redirect('/message')->withErrors(trans('messages.invalid_link'));
if($message->Replies->count())
Message::where('reply_id','=',$message->id)->where('to_user_id','=',\Auth::user()->id)->update(['is_read' => 1]);
if($message->reply)
return redirect('/message/'.$message->Reply->token);
if(\Auth::user()->id == $message->to_user_id){
$message->is_read = 1;
$message->save();
}
$assets = ['summernote'];
return view('message.view',compact('message','assets'));
}
public function trash($id,Request $request){
$message = $this->validateLiveMessage('id',$id);
if(!$message)
return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']);
$this->logActivity(['module' => 'message','module_id' => $message->id,'activity' => 'trashed']);
if($message->to_user_id == \Auth::user()->id)
$message->delete_receiver = 1;
else
$message->delete_sender = 1;
$message->save();
if($message->Replies->count()){
$sender_messages = $message->Replies->where('from_user_id','=',\Auth::user()->id)->pluck('id');
Message::whereIn('id',$sender_messages)->update(['delete_sender' => 1]);
$receiver_messages = $message->Replies->where('to_user_id','=',\Auth::user()->id)->pluck('id');
Message::whereIn('id',$receiver_messages)->update(['delete_receiver' => 1]);
}
return response()->json(['message' => trans('messages.message').' '.trans('messages.trashed'), 'status' => 'success']);
}
public function restore(Request $request){
$message = $this->validateDeleteMessage('token',$request->input('token'));
if(!$message)
return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']);
if($message->reply_id != null && (($message->Reply->to_user_id == \Auth::user()->id && $message->Reply->delete_receiver > 0) || ($message->Reply->from_user_id == \Auth::user()->id && $message->Reply->delete_sender > 0)))
return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']);
$this->logActivity(['module' => 'message','module_id' => $message->id,'activity' => 'restored']);
if($message->to_user_id == \Auth::user()->id)
$message->delete_receiver = 0;
else
$message->delete_sender = 0;
$message->save();
if($message->Replies->count()){
$sender_messages = $message->Replies->where('from_user_id','=',\Auth::user()->id)->pluck('id');
Message::whereIn('id',$sender_messages)->update(['delete_sender' => 0]);
$receiver_messages = $message->Replies->where('to_user_id','=',\Auth::user()->id)->pluck('id');
Message::whereIn('id',$receiver_messages)->update(['delete_receiver' => 0]);
}
return response()->json(['message' => trans('messages.message').' '.trans('messages.restored'), 'status' => 'success']);
}
public function destroy($id,Request $request){
$message = $this->validateDeleteMessage('id',$id);
if(!$message)
return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']);
if(getMode()){
$uploads = \App\Upload::whereModule('message')->whereModuleId($message->id)->get();
foreach($uploads as $upload)
\Storage::delete('attachments/'.$upload->attachments);
\App\Upload::whereModule('message')->whereModuleId($message->id)->delete();
}
$this->logActivity(['module' => 'message','module_id' => $message->id,'activity' => 'deleted']);
if($message->to_user_id == \Auth::user()->id)
$message->delete_receiver = 2;
else
$message->delete_sender = 2;
$message->save();
if($message->Replies->count()){
$sender_messages = $message->Replies->where('from_user_id','=',\Auth::user()->id)->pluck('id');
Message::whereIn('id',$sender_messages)->update(['delete_sender' => 2]);
$receiver_messages = $message->Replies->where('to_user_id','=',\Auth::user()->id)->pluck('id');
Message::whereIn('id',$receiver_messages)->update(['delete_receiver' => 2]);
}
return response()->json(['message' => trans('messages.message').' '.trans('messages.deleted'), 'status' => 'success']);
}
}
Does this line
$user = $new_message->to_user_id;
Return the Eloquent Model of the User or just the ID ? Is it a relation ? If not, as in the next lines you seem to try to access a relation.
if($user->Profile->mobile)
It is a wild guess, but maybe you need to do something like this
$user = User::findOrFail($new_message->to_user_id);
or setup a relation in Message model to be able to get the User object

Magento API duplicate SKU's

Using the Magento API to import ~60.000 products I manage to import duplicate SKU's in Magento, normally this throws an 'Duplicate SKU' exception but somehow it just add's double products.
Anyone knows what's going wrong (some index caching or something?)?
This is the (relevant) part of the code of the import script:
<?php
/**
* #param $data
* #param bool $retry
* #return bool
*/
public function updateProduct($data, $retry = true) {
//Calculate product hash
$hash = md5(serialize($data));
try {
$manageStock = 0;
if($data->qty <= 0) {
$manageStock = 1;
}
$result = $this->client->catalogProductUpdate($this->session, $data->prefixed_sku, array(
'categories' => $data->categories,
'status' => empty($data->status) ? '1' : (int) $data->status,
'cost' => $data->cost,
'price' => $data->price,
'tax_class_id' => '2',
'visibility' => '4',
'stock_data' => array(
'qty' => $data->qty,
'is_in_stock' => $data->is_in_stock,
'manage_stock' => $manageStock
),
'additional_attributes' => array('cost' => $data->cost)
), null, 'sku');
}
catch (Exception $e) {
$result = $this->exceptionLogAndRetry($e, 'updateProduct', $retry, $data);
}
return $result;
}
/**
* #param $data
* #param bool $retry
* #return bool
*/
public function addProduct($data, $retry = true) {
//Calculate product hash
$hash = md5(serialize($data));
if(!$this->attributeSet) {
$attributeSets = $this->client->catalogProductAttributeSetList($this->session);
foreach($attributeSets as $attributeSet) {
if(strtolower($attributeSet->name) == 'default') {
$this->attributeSet = $attributeSet;
}
}
if(!$this->attributeSet) {
$this->attributeSet = current($attributeSets);
}
}
try {
$stock = array(
'qty' => $data->qty,
'is_in_stock' => $data->is_in_stock,
'use_config_manage_stock' => $data->use_config_manage_stock
);
if($data->qty <= 0) {
$stock['manage_stock'] = 1;
}
$result = $this->client->catalogProductCreate($this->session, 'simple', $this->attributeSet->set_id, $data->prefixed_sku, array(
'categories' => $data->categories,
'websites' => array($data->website_id),
'name' => $data->name,
'description' => $data->description,
'short_description' => $data->short_description,
'weight' => $data->weight,
'cost' => $data->cost,
'status' => empty($data->status) ? '1' : (int) $data->status,
'url_key' => $data->url_key,
'url_path' => $data->url_path,
'visibility' => '4',
'price' => $data->price,
'tax_class_id' => '2',
'meta_title' => $data->meta_title,
'meta_keyword' => $data->meta_keyword,
'meta_description' => $data->meta_description,
'stock_data' => $stock,
'additional_attributes' => array('cost' => $data->cost)
));
}
catch (Exception $e) {
$result = $this->exceptionLogAndRetry($e, 'addProduct', $retry, $data);
}
for ($i = 1; $i <= 5; $i++)
{
$cur = $i;
if ($cur == 1)
{
$cur = '';
}
if (!empty($data->{"product_image$cur"}) && file_exists($data->{"product_image$cur"}) && is_numeric($result))
{
$file = array(
'content' => base64_encode(#file_get_contents($data->{"product_image$cur"})),
'mime' => $data->{'product_mime'.$cur}
);
try {
$imgRes = $this->client->catalogProductAttributeMediaCreate(
$this->session,
$result,
array('file' => $file, 'label' => '', 'position' => '100', 'types' => array('thumbnail', 'small_image', 'image'), 'exclude' => 0)
);
}
catch (Exception $e) {
//Do nothing
}
}
}
$return = $result;
return $return;
}

Exporting and Importing Attributes in Magento

I would love a script or magento extension to allow me to export all the product attributes including values for drop down attributes. Importing would be good too, I've had a look but can't seem to find anything does anyone know how this can be done?
Update: I found a working script in stackexchange and the script worked exactly as it should. All credits to the original poster. I am just copy pasting his reply here for future reference. Link to the original thread: is here.
I've done this to export all attributes and their options (if it is a dropdown attribute) from the source website:
exportAttributes.php in root directory of source website:
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app();
$entity_type_id = Mage::getModel('catalog/product')->getResource()->getTypeId();
prepareCollection($entity_type_id);
function prepareCollection($ent_type_id){
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$select_attribs = $connection->select()
->from(array('ea'=>$resource->getTableName('eav/attribute')))
->join(array('c_ea'=>$resource->getTableName('catalog/eav_attribute')), 'ea.attribute_id = c_ea.attribute_id');
// ->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
// ->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
$select_prod_attribs = $select_attribs->where('ea.entity_type_id = '.$ent_type_id)
->order('ea.attribute_id ASC');
$product_attributes = $connection->fetchAll($select_prod_attribs);
$select_attrib_option = $select_attribs
->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
->order('e_ao.attribute_id ASC');
$product_attribute_options = $connection->fetchAll($select_attrib_option);
$attributesCollection = mergeCollections($product_attributes, $product_attribute_options);
prepareCsv($attributesCollection);
}
function mergeCollections($product_attributes, $product_attribute_options){
foreach($product_attributes as $key => $_prodAttrib){
$values = array();
$attribId = $_prodAttrib['attribute_id'];
foreach($product_attribute_options as $pao){
if($pao['attribute_id'] == $attribId){
$values[] = $pao['value'];
}
}
if(count($values) > 0){
$values = implode(";", $values);
$product_attributes[$key]['_options'] = $values;
}
else{
$product_attributes[$key]['_options'] = "";
}
/*
temp
*/
$product_attributes[$key]['attribute_code'] = $product_attributes[$key]['attribute_code'];
}
return $product_attributes;
}
function prepareCsv($attributesCollection, $filename = "importAttrib.csv", $delimiter = '|', $enclosure = '"'){
$f = fopen('php://memory', 'w');
$first = true;
foreach ($attributesCollection as $line) {
if($first){
$titles = array();
foreach($line as $field => $val){
$titles[] = $field;
}
fputcsv($f, $titles, $delimiter, $enclosure);
$first = false;
}
fputcsv($f, $line, $delimiter, $enclosure);
}
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="'.$filename.'"');
fpassthru($f);
}
This will give a csv file [actually i used "|" to separate ;)]
paste this csv file in MAGENTO_ROOT/attribImport directory of the destination website, i.e. website to which attributes need to be imported:
now put the following code in MAGENTO_ROOT/attribImport** directory
of the destination website
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();
// $fileName = MAGENTO . '/var/import/importAttrib.csv';
$fileName = 'importAttrib.csv';
// getCsv($fileName);
getAttributeCsv($fileName);
function getAttributeCsv($fileName){
// $csv = array_map("str_getcsv", file($fileName,FILE_SKIP_EMPTY_LINES));
$file = fopen($fileName,"r");
while(!feof($file)){
$csv[] = fgetcsv($file, 0, '|');
}
$keys = array_shift($csv);
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
foreach($csv as $row){
$labelText = $row['frontend_label'];
$attributeCode = $row['attribute_code'];
if($row['_options'] != "")
$options = explode(";", $row['_options']); // add this to createAttribute parameters and call "addAttributeValue" function.
else
$options = -1;
if($row['apply_to'] != "")
$productTypes = explode(",", $row['apply_to']);
else
$productTypes = -1;
unset($row['frontend_label'], $row['attribute_code'], $row['_options'], $row['apply_to'], $row['attribute_id'], $row['entity_type_id'], $row['search_weight']);
createAttribute($labelText, $attributeCode, $row, $productTypes, -1, $options);
}
}
/**
* Create an attribute.
*
* For reference, see Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
*
* #return int|false
*/
function createAttribute($labelText, $attributeCode, $values = -1, $productTypes = -1, $setInfo = -1, $options = -1)
{
$labelText = trim($labelText);
$attributeCode = trim($attributeCode);
if($labelText == '' || $attributeCode == '')
{
echo "Can't import the attribute with an empty label or code. LABEL= [$labelText] CODE= [$attributeCode]"."<br/>";
return false;
}
if($values === -1)
$values = array();
if($productTypes === -1)
$productTypes = array();
if($setInfo !== -1 && (isset($setInfo['SetID']) == false || isset($setInfo['GroupID']) == false))
{
echo "Please provide both the set-ID and the group-ID of the attribute-set if you'd like to subscribe to one."."<br/>";
return false;
}
echo "Creating attribute [$labelText] with code [$attributeCode]."."<br/>";
//>>>> Build the data structure that will define the attribute. See
// Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
$data = array(
'is_global' => '0',
'frontend_input' => 'text',
'default_value_text' => '',
'default_value_yesno' => '0',
'default_value_date' => '',
'default_value_textarea' => '',
'is_unique' => '0',
'is_required' => '0',
'frontend_class' => '',
'is_searchable' => '1',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
'used_for_sort_by' => '0',
'is_configurable' => '0',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'backend_type' => 'varchar',
'default_value' => '',
'is_user_defined' => '0',
'is_visible' => '1',
'is_used_for_price_rules' => '0',
'position' => '0',
'is_wysiwyg_enabled' => '0',
'backend_model' => '',
'attribute_model' => '',
'backend_table' => '',
'frontend_model' => '',
'source_model' => '',
'note' => '',
'frontend_input_renderer' => '',
);
// Now, overlay the incoming values on to the defaults.
foreach($values as $key => $newValue)
if(isset($data[$key]) == false)
{
echo "Attribute feature [$key] is not valid."."<br/>";
return false;
}
else
$data[$key] = $newValue;
// Valid product types: simple, grouped, configurable, virtual, bundle, downloadable, giftcard
$data['apply_to'] = $productTypes;
$data['attribute_code'] = $attributeCode;
$data['frontend_label'] = array(
0 => $labelText,
1 => '',
3 => '',
2 => '',
4 => '',
);
//<<<<
//>>>> Build the model.
$model = Mage::getModel('catalog/resource_eav_attribute');
$model->addData($data);
if($setInfo !== -1)
{
$model->setAttributeSetId($setInfo['SetID']);
$model->setAttributeGroupId($setInfo['GroupID']);
}
$entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
$model->setEntityTypeId($entityTypeID);
$model->setIsUserDefined(1);
//<<<<
// Save.
try
{
$model->save();
}
catch(Exception $ex)
{
echo "Attribute [$labelText] could not be saved: " . $ex->getMessage()."<br/>";
return false;
}
if(is_array($options)){
foreach($options as $_opt){
addAttributeValue($attributeCode, $_opt);
}
}
$id = $model->getId();
echo "Attribute [$labelText] has been saved as ID ($id).<br/>";
// return $id;
}
function addAttributeValue($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
if(!attributeValueExists($arg_attribute, $arg_value))
{
$value['option'] = array($arg_value,$arg_value);
$result = array('value' => $value);
$attribute->setData('option',$result);
$attribute->save();
}
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
function attributeValueExists($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
NOTE: Allthough exceptions have been handled, Backup your Database
before you import these attributes, to be on safer side. Happy
Importing!
Thanks to :
Programatically create attribute in Magento, useful for the “on the fly” import system
programmatically_adding_attributes_and_attribute_sets
Magento – Programmatically insert new attribute option
I would recommend Boris's uRapidFlow: http://www.unirgy.com/products/urapidflow/ It's one of the better Data Flow Import/Export modules available. Be aware however it does require IonCube Loader, but it is well worth it if you are moving data around a lot.

Resources