Laravel Sms Configuration - laravel

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

Related

where and whereIn suddenly stops working in laravel api

In my laravel api am using eloquent query with where condition like this. it was woriking fine before not it is not returning data . when i remove where and whereIn from query then it works fine.In tinker it is fetching data with where and whereIn .
Here is the query
WorkingOrders::whereIn('status',[8,9])->where('gang_boss',auth()->user()->id)->orderBy('id','desc')->get();
whole controller is here
<?php
namespace App\Http\Controllers\GeneralApi;
use App\Events\ConfirmOrder;
use App\Http\Controllers\Controller;
use App\Models\Admin\Gang;
use App\Models\Admin\RightHandMan;
use App\Models\Admin\Staff;
use App\Models\Admin\StaffPivot;
use App\Models\Admin\Worker;
use App\Models\Admin\WorkerArrival;
use App\Models\Admin\WorkSheet;
use App\Models\WorkingOrders;
use App\Notifications\CustomNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class WorkOrderController extends Controller
{
public function workOrdersCompletedCancelled($user_id)
{
$role_id = Auth::guard('staff_api')->user()->roles()->first()->id;
$work_orders = WorkingOrders::when($role_id == 2, function ($q) use ($user_id) {
return $q->where('ranch', $user_id);
})->when($role_id == 4, function ($q) use ($user_id) {
return $q->where('right_hand_man_id', $user_id);
})->when($role_id == 8, function ($q) use ($user_id) {
return $q->where('supervisor', $user_id);
})->when($role_id == 3, function ($q) use ($user_id) {
$gang_ids = DB::table('worker_gang')->where('worker_id', $user_id)->pluck('gang_id')->toArray();
$boss_ids = Gang::where('id', $gang_ids)->pluck('boss_id')->toArray();
return $q->whereIn('gang_boss', $boss_ids);
})->when($role_id == 10, function ($q) use ($user_id) {
return $q->where('truck', $user_id);
})->when($role_id == 1, function ($q) use ($user_id) {
return $q->where('agent', $user_id);
})->when($role_id == 9, function ($q) use ($user_id) {
return $q->where('gang_boss', $user_id);
})->whereIn('status', [0, 9])->with('gang_boss_details.bosses')
->with('type_of_cut_details')
->with('type_of_damage_details')
->with('number_of_boxes_details')
->with('size_of_boxes_details')
->with('packaging_company_details.packaging_companies')
->with('cutting_company_details:id,name')->with('supervisor_details:id,name')->with('agent_details:id,name')
->with('packaging_company_details:id,name')->with('truck_details:id,name')->with('ranch_details.ranch_owners')->with('right_hand_man:id,name')->with('weighing_machine_details:id,name,address,longitude,latitude')->with('worksheet')->orderBy('id', 'desc')->limit(20)->get();
return response()->json($work_orders);
}
public function workOrders($boss_id)
{
$work_orders = WorkingOrders::where('gang_boss', $boss_id)
->with('type_of_cut_details')
->with('type_of_damage_details')
->with('number_of_boxes_details')
->with('size_of_boxes_details')
->with('packaging_company_details.packaging_companies')
->with('gang_boss_details.bosses')->with('cutting_company_details:id,name')->with('supervisor_details:id,name')->with('agent_details:id,name')
->with('packaging_company_details')->with('truck_details:id,name')->with('ranch_details.ranch_owners')->with('right_hand_man:id,name')->with('weighing_machine_details:id,name,address,longitude,latitude')->with('worksheet')->orderBy('id', 'desc')->limit(20)->get();
return response()->json($work_orders);
}
public function workOrderDetail($work_order_id)
{
$work_order = WorkingOrders::with('cutting_company_details:id,name')
->with('type_of_cut_details')
->with('type_of_damage_details')
->with('number_of_boxes_details')
->with('size_of_boxes_details')
->with('packaging_company_details.packaging_companies')
->with('supervisor_details')->with('gang_boss_details.bosses')->with('agent_details')->with('ranch_details.ranch_owners')
->with('packaging_company_details')->with('weighing_machine_details:id,name,address,longitude,latitude')->with('worksheet')->with('truck_details.trucks')->with('right_hand_man')->find($work_order_id);
return response()->json($work_order);
}
public function markOrderComplete($id)
{
$work_order = WorkingOrders::find($id);
DB::table('notifications')->where('data','like','%'.$id.'%')->delete();
$work_order->update(['status'=>9,'truck_delivered_fruit_at'=>date('Y-m-d H:i:s')]);
}
public function getRightHandManList()
{
$staff_child = StaffPivot::where('staff_id', auth()->user()->id)->pluck('child_id')->toArray();
$staff_role = DB::table('staff_role')->whereIn('staff_id', $staff_child)->where('role_id', 4)->pluck('staff_id')->toArray();
$staffs = Staff::whereIn('id', $staff_role)->pluck('id');
$right_hand_men = RightHandMan::whereIn('staff_id', $staffs)->with('staffs')->get();
return response()->json($right_hand_men);
}
public function saveRightHandManList($right_hand_man, $work_order_id)
{
$work_order = WorkingOrders::find($work_order_id);
if($work_order->status == 8){
$status = 8;
}else{
$status = 3;
}
$work_order->update(['right_hand_man_id' => $right_hand_man, 'status' => $status,'confirmed_by_boss_at'=>date('Y-m-d H:i:s')]);
$working_order = WorkingOrders::find($work_order_id);
$appDetails = [
'actionText' => Auth::user()->name . ' Se te asignó la orden de corte #' . $work_order_id,
'actionURL' => "/work-order-detail/2/{$working_order->longitude}/{$working_order->latitude}",
];
$rhm = Staff::find($right_hand_man);
$rhm->notify(new CustomNotification($appDetails));
event(new ConfirmOrder($working_order));
return response()->json(['success' => 'Bañero asignado correctamente']);
}
public function getWorkSheet($work_order_id,$time)
{
$work_sheet = WorkSheet::where('work_order_id', $work_order_id)->first();
$work_order = WorkingOrders::find($work_order_id);
if($work_order->status == 8){
$status = 8;
}else{
$status = 6;
}
$work_order->update(['status'=>$status,'arrival_to_ranch_at'=>date('Y-m-d H:i:s',strtotime($time))]);
return response()->json($work_sheet);
}
public function saveWorkSheet($work_order_id, $column_name, $column_value)
{
if ($column_value == 'null') {
$column_value = null;
}
$work_sheet = WorkSheet::where('work_order_id', $work_order_id)->update([$column_name => $column_value]);
return response()->json(['status' => true, 'message' => 'Hoja de campo guardada correctamente']);
}
public function addWorker(Request $request)
{
$this->validate($request, [
'name' => 'required',
'password' => 'required',
'location' => 'required',
'longitude' => 'required',
'latitude' => 'required',
'govt_id' => 'required',
'phone_number' => 'required',
'social_security_number' => 'required|unique:staffs,social_security_number',
'time_as_worker' => 'required',
'email' => 'required|email|unique:staffs,email'
]);
$staff = Staff::create([
'name' => $request->name, 'password' => bcrypt($request->password), 'email' => $request->email, 'govt_id' => $request->govt_id,
'social_security_number' => $request->social_security_number, 'phone_number' => $request->phone_number
]);
DB::insert('insert into staff_role (role_id, staff_id) values (?, ?)', [3, $staff->id]);
Worker::create(['staff_id' => $staff->id, 'time_as_worker' => $request->time_as_worker, 'address' => $request->location, 'latitude' => $request->latitude, 'longitude' => $request->longitude]);
StaffPivot::create(['staff_id' => $request->boss_id, 'child_id' => $staff->id]);
return response()->json(['status' => true, 'message' => 'Cortador creado correctamente']);
}
public function addRightHandMan(Request $request)
{
$this->validate($request, [
'name' => 'required',
'password' => 'required',
'location' => 'required',
'longitude' => 'required',
'latitude' => 'required',
'govt_id' => 'required',
'phone_number' => 'required',
'social_security_number' => 'required|unique:staffs,social_security_number',
'time_as_right_hand_man' => 'required',
'email' => 'required|email|unique:staffs,email'
]);
$staff = Staff::create([
'name' => $request->name, 'password' => bcrypt($request->password), 'email' => $request->email, 'govt_id' => $request->govt_id,
'social_security_number' => $request->social_security_number, 'phone_number' => $request->phone_number
]);
DB::insert('insert into staff_role (role_id, staff_id) values (?, ?)', [4, $staff->id]);
RightHandMan::create(['staff_id' => $staff->id, 'time_as_right_hand_man' => $request->time_as_right_hand_man, 'address' => $request->location, 'latitude' => $request->latitude, 'longitude' => $request->longitude]);
StaffPivot::create(['staff_id' => $request->boss_id, 'child_id' => $staff->id]);
return response()->json(['status' => true, 'message' => 'Bañero creado correctamente']);
}
public function getGangWorkers($gang_boss_id, $work_order_id)
{
$gang = Gang::where('boss_id', $gang_boss_id)->first();
$arrived_workers = WorkerArrival::select('worker_id')->where('work_order_id', $work_order_id)->pluck('worker_id');
return response()->json(['workers' => $gang->workers()->get(), 'arrived_workers' => $arrived_workers]);
}
public function getGangWorkersOnly($gang_boss_id)
{
$gang = Gang::where('boss_id', $gang_boss_id)->first();
return response()->json(['workers' => $gang->workers()->get()]);
}
public function storeWorkerArrival(Request $request)
{
WorkerArrival::where('work_order_id', $request->work_order_id)->delete();
foreach ($request->worker_ids as $id) {
if(!WorkerArrival::where('worker_id',$id)->where('work_order_id',$request->work_order_id)->exists()){
WorkerArrival::create(['worker_id' => $id, 'work_order_id' => $request->work_order_id, 'is_reached' => 1]);
}
}
$work_order = WorkingOrders::find($request->work_order_id);
if($work_order->status == 8){
$status = 8;
}else{
$status = 5;
}
$work_order->update(['status'=>$status,'arrival_to_mp_at'=>date('Y-m-d H:i:s',strtotime($request->time))]);
event(new ConfirmOrder(WorkingOrders::find($request->work_order_id)));
return response()->json(['status' => true, 'message' => 'Los cortadores que llegaron han sido registrados']);
}
public function getBossRightHandMan($boss_id)
{
$staff_child = StaffPivot::where('staff_id', $boss_id)->pluck('child_id')->toArray();
$staff_role = DB::table('staff_role')->whereIn('staff_id', $staff_child)->where('role_id', 4)->pluck('staff_id')->toArray();
$staffs = Staff::whereIn('id', $staff_role)->get();
return response()->json($staffs);
}
public function getBossWorkers($boss_id)
{
// $gang = Gang::where('boss_id', $boss_id)->first();
// return response()->json(['workers' => $gang->workers()->get()]);
$staff_child = StaffPivot::where('staff_id', $boss_id)->pluck('child_id')->toArray();
$staff_role = DB::table('staff_role')->whereIn('staff_id', $staff_child)->where('role_id', 3)->pluck('staff_id')->toArray();
$staffs = Staff::whereIn('id', $staff_role)->get();
$gang = Gang::where('boss_id', $boss_id)->first();
return response()->json(['staff'=>$staffs,'workers'=>$gang->workers()->pluck('worker_id')->toArray()]);
}
public function deleteWorker(Request $request)
{
// Staff::find($request->worker_id)->delete();
// Worker::where('staff_id', $request->worker_id)->delete();
// $gang = Gang::where('boss_id', auth()->user()->id)->first();
// DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->delete();
$gang = Gang::where('boss_id', auth()->user()->id)->first();
StaffPivot::where('staff_id', auth()->user()->id)->where('child_id' , $request->worker_id)->delete();
DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->delete();
return response()->json(['success', 'Cortador elimando de tu lista de trabajadores']);
}
public function checkExistingStaff(Request $request)
{
if (Staff::where('social_security_number', $request->social_security_number)->exists()) {
return response()->json(['exists' => true, 'data' => Staff::where('social_security_number', $request->social_security_number)->first()]);
}
return response()->json(['exists' => false]);
}
public function addToMyProfile(Request $request)
{
if (!StaffPivot::where('staff_id', auth()->user()->id)->where('child_id', $request->child_id)->exists()) {
StaffPivot::create(['staff_id' => auth()->user()->id, 'child_id' => $request->child_id]);
return response()->json(['message' => 'Agregado correctamente a tu lista de trabajadores']);
}
return response()->json(['message' => 'Ya existe este usuario en tu lista de trabajadores']);
}
public function satffDetail($staff_id)
{
$satff = Staff::find($staff_id);
return response()->json($satff);
}
public function addToGang(Request $request)
{
$gang = Gang::where('boss_id', auth()->user()->id)->first();
if (!DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->exists()) {
DB::table('worker_gang')->insert(['worker_id' => $request->worker_id, 'gang_id' => $gang->id]);
}
return response()->json(['status' => true, 'message' => 'Cortador asignado a la cuadrilla']);
}
public function removeWorkerFromGang(Request $request)
{
$gang = Gang::where('boss_id', auth()->user()->id)->first();
if (DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->exists()) {
DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->delete();
return response()->json(['status' => true, 'message' => 'Eliminado de la cuadrilla']);
}
return response()->json(['status' => true, 'message' => 'Este cortador no está en la cuadrilla']);
}
public function removeRHMFromWorkOrder(Request $request)
{
StaffPivot::where('child_id', $request->rhm)->where('staff_id', auth()->user()->id)->delete();
return response()->json(['success', 'Bañero elimanado de tu lista de trabajadores']);
}
public function OrderComplete($id,$time)
{
$work_order = WorkingOrders::find($id);
if($work_order->status == 8){
$status = 8;
}else{
$status = 7;
}
$work_order->update(['status' => $status,'boss_marked_completed_at'=>date('Y-m-d H:i:s',strtotime($time))]);
return response()->json(['status' => true, 'message' => 'Orden de corte completada']);
}
public function acceptance(Request $request)
{
if ($request->role == 'ranch') {
WorkingOrders::where('id', $request->work_order_id)->update(['ranch_signature' => $request->acceptance]);
}
if ($request->role == 'supervisor') {
WorkingOrders::where('id', $request->work_order_id)->update(['supervisor_signature' => $request->acceptance]);
}
return response()->json(['success' => 'Acción completada']);
}
public function storeWorkerData(Request $request)
{
WorkingOrders::find($request->work_order_id)->update(['boss_marked_completed_at'=>date('Y-m-d H:i:s'),'arrival_to_ranch_at'=>date('Y-m-d H:i:s')]);
WorkSheet::where('work_order_id', $request->work_order_id)->update(['worker_data' => json_encode($request->worker_data),'number_of_box'=>json_encode($request->number_of_boxes)]);
return response()->json(['success' => 'Datos del cortador guardados']);
}
public function getBossPayments(Request $request)
{
if($request->keyword !='false'){
$staff_ids = Staff::select('id')->where('name','like',"%{$request->keyword}%")->pluck('id');
$work_orders = WorkingOrders::select('id','cutting_company','ranch','cutting_company_amount','final_kg','boss_amount')->with(['cutting_company_details:id,name','ranch_details:id,name','worksheet:work_order_id,worker_data,number_of_box'])->whereIn('status',[8,9])->where('gang_boss',auth()->user()->id)
->where(function($query)use($request,$staff_ids){
$query->orWhere('id',$request->keyword)->orWhereIn('ranch',$staff_ids)->orWhereIn('cutting_company',$staff_ids);
})->orderBy('id','desc')->get();
foreach($work_orders as $work_order)
{
$work_order->setAttribute('payment',$this->getTotalAmountToPayToWorkers($work_order)['total_payment']);
}
return response()->json(['work_orders'=>$work_orders]);
}else{
$work_orders = WorkingOrders::select('id','cutting_company','ranch','cutting_company_amount','final_kg','boss_amount')->with(['cutting_company_details:id,name','ranch_details:id,name','worksheet:work_order_id,worker_data,number_of_box'])->whereIn('status',[8,9])->where('gang_boss',auth()->user()->id)->orderBy('id','desc')->get();
dd($work_orders);
foreach($work_orders as $work_order)
{
$work_order->setAttribute('payment',$this->getTotalAmountToPayToWorkers($work_order)['total_payment']);
}
return response()->json(['work_orders'=>$work_orders]);
}
}
public function getWorkOrderWorkerPayment($work_order_id)
{
$work_order = WorkingOrders::with(['worksheet:work_order_id,worker_data,number_of_box','cutting_company_details:id,name','ranch_details:id,name'])->select('id','boss_amount','boss_marked_completed_at','cutting_company','ranch','date_of_work')->where('id',$work_order_id)->first();
$work_order->setAttribute('total_amount_to_pay', $this->getTotalAmountToPayToWorkers($work_order)['total_payment']);
return response()->json(['worker_payment_data'=>$this->getTotalAmountToPayToWorkers($work_order)['worker_payment_data'],'work_order'=>$work_order]);
}
public function getTotalAmountToPayToWorkers($work_order)
{
$total_amount_to_pay = 0;
$worker_payment_data = [];
$work_sheet= $work_order->worksheet;
$data = json_decode($work_sheet->worker_data,true );
$number_of_boxes = json_decode($work_sheet->number_of_box,true);
foreach ((array)$data as $key => $worker_data){
$box = 0;
if(key_exists($key,$number_of_boxes))
{
$box =(int)$number_of_boxes[$key];
}
array_push($worker_payment_data,array('worker_id'=>explode("-",$key)[0],'photo_url'=>Staff::find(explode("-",$key)[0])->photo_url ?? '','worker_name'=>explode("-",$key)[1],'number_of_boxes'=>$box,'comment'=>$worker_data,
'amount_to_pay'=>$box * (float)$work_order->boss_amount ));
$total_amount_to_pay += ($box * (float)$work_order->boss_amount);
}
$worker_payment_data = collect($worker_payment_data);
return array('total_payment'=>$total_amount_to_pay,'worker_payment_data'=>$worker_payment_data);
}
public function submitBossAmount($work_order_id,Request $request)
{
WorkingOrders::find($work_order_id)->update(['boss_amount'=>$request->boss_amount]);
return response()->json(['status'=>true,'message'=>'Boss amount submitted successfully']);
}
public function getWorkerPayments(Request $request,$worker_id)
{
$staff_ids = Staff::select('id')->where('name','like',"%{$request->keyword}%")->pluck('id');
$work_order_ids = WorkSheet::select('work_order_id')->where('worker_data','like',"%{$worker_id}%")->pluck('work_order_id');
$work_orders = WorkingOrders::select('id','cutting_company','ranch','cutting_company_amount','final_kg','boss_amount','date_of_work','boss_marked_completed_at')
->with(['cutting_company_details:id,name','ranch_details:id,name'])
->whereIn('status',[8,9])->whereIn('id',$work_order_ids)
->where(function($query)use($staff_ids,$request){
$query->where('id',$request->keyword)->orWhereIn('ranch',$staff_ids)->orWhereIn('cutting_company',$staff_ids);
})->orderBy('id','desc')->get();
foreach($work_orders as $work_order)
{
$payment = $this->getTotalAmountToPayToWorkersForWorkPortal($work_order,$worker_id);
$work_order->setAttribute('payment',$payment['total_payment']);
$work_order->setAttribute('worker_payment_data',$payment['worker_payment_data']);
$work_order->setAttribute('total_amount_to_pay',$payment['total_payment']);
}
return response()->json(['work_orders'=>$work_orders,'worker_payment_data']);
}
public function getTotalAmountToPayToWorkersForWorkPortal($work_order,$worker_id)
{
$total_amount_to_pay = 0;
$worker_payment_data = [];
$work_sheet= $work_order->worksheet;
$worker_data = json_decode($work_sheet->worker_data,true );
$number_of_boxes = json_decode($work_sheet->number_of_box,true);
foreach ($worker_data as $key => $worker_data){
$box = 0;
if(key_exists($key,$number_of_boxes))
{
$box =(int)$number_of_boxes[$key];
}
if(explode("-",$key)[0] == $worker_id){
$worker_payment_data = array('worker_id'=>explode("-",$key)[0],'photo_url'=>Staff::find(explode("-",$key)[0])->photo_url ?? '','worker_name'=>explode("-",$key)[1],'number_of_boxes'=> $box ,'comment'=>$worker_data,
'amount_to_pay'=> $box * (float)$work_order->boss_amount );
$total_amount_to_pay += ( $box * (float)$work_order->boss_amount);
}
}
$worker_payment_data = collect($worker_payment_data);
return array('total_payment'=>$total_amount_to_pay,'worker_payment_data'=>$worker_payment_data);
}
}
This is the full controller . I also tried to type cast variable which are using in where condition but nothing works.

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'];
}

Dropdownlist selected value not showing while updating the form

Here i like to explain my problem
i have dropdownlist called companytype, it contains value 1+1, 1+2, 1+3, 1+4, 1+5, 1+6, 1+7
while creating form i have a select a value eg:1+4 and store, but the same while updating the value getting change as select companytype [prompt]
<?= $form->field($model, 'companytype')->dropDownList([ '1' => '1+1', '2' => '1+2', '3' => '1+3', '4' => '1+4', '5' => '1+5', '6' => '1+6', '7' => '1+7', ], ['prompt' => 'Select Company Type', ]) ?>
here i have added two images you can easily understand my question
gridview of created form
updating the same form
updated:
mycontroller code:
public function actionCreate()
{
if(Yii::$app->user->can( 'create-company' ) )
{
$model = new Company();
if ($model->load(Yii::$app->request->post()) ) {
$model->createdat = date('Y-m-d');
$ro = $model->relationoption;
if($ro == 'fixed')
{
$commaList = implode(', ', $model->relation);
$model->relation = $commaList;
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
else
{
throw new ForbiddenHttpException;
}
}
controller code for update
public function actionUpdate($id)
{
if(Yii::$app->user->can('update-company'))
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) )
{
$model->updatedat = date('Y-m-d h:m:s');
$ro = $model->relationoption;
if($ro == 'fixed')
{
$commaList = implode(', ', $model->relation);
$model->relation = $commaList;
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
else
{
throw new ForbiddenHttpException;
}
}
Is there anyone to answer, pls answer me
I dont see $model->companytype = 4 in your update action. Can you add it to your update action and check. So your update action should look like:
public function actionUpdate($id)
{
if(Yii::$app->user->can('update-company'))
{
$model = $this->findModel($id);
$model->companytype = 4;
if ($model->load(Yii::$app->request->post()) )
{
$model->updatedat = date('Y-m-d h:m:s');
$ro = $model->relationoption;
if($ro == 'fixed')
{
$commaList = implode(', ', $model->relation);
$model->relation = $commaList;
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
else
{
throw new ForbiddenHttpException;
}
}

Error adding Custom Option in 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);

Resources