Entry in database not being overwritten when looking at ID - php

I'm currently looking at a script that a previous developer made that is meant to look a table, if the id does not exist then create the new code, if it does exist, overwrite the existing one.
Sounds fairly simple, but I can't get my head around how Yii manages the overwrite and new verification code. It is only adding new records, not over writing.
$invitingUser = User::model()->findByPk(Yii::app()->user->id);
if ($invitingUser->isAttending($eventId)) {
// Event attending
$event = Event::model()->findByPk($eventId);
//
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation(array($guestInviteForm));
if (isset($_POST['GuestInviteForm'])) {
$guestInviteForm->attributes = $_POST['GuestInviteForm'];
// Perform Validation
$valid = $guestInviteForm->validate();
if ($valid) {
// Check if a Verification Code entry for this user already exists
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
//THE CODE ONLY SEEMS TO RUN THIS.
if (is_null($existingVerificationCode)) {
// Create Verification Code instance
$verificationCode = new VerificationCode();
$verificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$verificationCode->user_id = $invitingUser->id;
$verificationCode->verification_code = VerificationCode::generateVerificationCode();
$verificationCode->forename = $guestInviteForm->forename;
$verificationCode->surname = $guestInviteForm->surname;
$verificationCode->event_id = $eventId;
$verificationCode->save(false);
} else {
// Update existing Verification Code enty
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
}
The code never seems to enter the else here
//THE CODE ONLY SEEMS TO RUN THIS.
if (is_null($existingVerificationCode)) {
// Create Verification Code instance
$verificationCode = new VerificationCode();
$verificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$verificationCode->user_id = $invitingUser->id;
$verificationCode->verification_code = VerificationCode::generateVerificationCode();
$verificationCode->forename = $guestInviteForm->forename;
$verificationCode->surname = $guestInviteForm->surname;
$verificationCode->event_id = $eventId;
$verificationCode->save(false);
} else {
// Update existing Verification Code enty
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
}

1st. After form validation:
if ($valid) {
Verification code select done:
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
If you translate it to SQL it will be something like this:
SELECT * FROM verification_code WHERE user_id=x AND type=x
2nd. Check if record exists
if (is_null($existingVerificationCode)) {
If its not - creating new, populating, saving.
Else updating:
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
save(false) means save without validation. Consider model attributes - fields in your database table.

Seems like it ever goes in the ELSE because it never finds $existingVerificationCode.
We don't have the whole code, but from what I see, I suspect you're checking the wrong user, because it's weird to search for an event for $user, and if that doesn't exist, to create one related to $invitingUser.
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
// ...
$verificationCode->user_id = $invitingUser->id;

Related

Netsuite Item Fulfillment Invalid Line Items

I'm trying to set a SalesOrder to fulfilled using the PHP Netsuite Api but I keep getting the following error:
VALID_LINE_ITEM_REQD - You must have at least one valid line item for
this transaction.
I'm using the https://github.com/ryanwinchester/netsuite-php library.
I have the following so far. I've tried using the Initialise methods as well that I've seen in some examples, but they all seem to give the same error. We're using Advanced Inventory Management if that helps.
$itemFulfillment = new ItemFulfillment();
// Sales Order
$itemFulfillment->createdFrom = new RecordRef();
$itemFulfillment->createdFrom->internalId = <SALES_ORDER_ID>;
$itemFulfillment->shipStatus = ItemFulfillmentShipStatus::_shipped;
// Customer
$itemFulfillment->entity = new RecordRef();
$itemFulfillment->entity->internalId = <CUSTOMER_ID>;
// List
$fullfillmentList = new ItemFulfillmentItemList();
$fullfillmentList->replaceAll = true;
foreach($salesOrder->itemList->item as $saleItem) {
$item = new ItemFulfillmentItem();
$item->location = new RecordRef();
$item->location->internalId = 4;
$item->item = new RecordRef();
$item->item->internalId = $saleItem->item->internalId;
$item->itemIsFulfilled = true;
$item->itemReceive = true;
$item->quantity = $saleItem->quantity;
$item->orderLine = $saleItem->line;
// Department Reference
$departmentRec = new RecordRef();
$departmentRec->internalId = 5;
$item->department = $departmentRec;
$fullfillmentList->item[] = $item;
}
$itemFulfillment->itemList = $fullfillmentList;
$request = new AddRequest();
$request->record = $itemFulfillment;
$client->add($request);
Any help would be great. :)
Transforming a Sales Order to a
Cross-Subsidiary Item Fulfillment Record will return a
"VALID_LINE_ITEM_REQD >
You must have at least one valid line item for this transaction" error if we did not specify an inventoryLocation in the defaultValue parameter.
function createIF(soId, invLocation) {
var itemFulfillment = record.transform({
fromType: record.Type.SALES_ORDER,
fromId: soId,
toType: record.Type.ITEM_FULFILLMENT,
defaultValues: {
inventorylocation: invLocation
}
});
/**
* You can insert other script logic here
*/
var ifID = itemFulfillment.save();
return ifID;
}
make sure the item is in inventory
make sure the item is available to your subsidiary
make sure you are committing sublists correctly, if applicable
dump $saleItem to see whats in it to make sure noting is null

How to post an event directly to another user's calendar

i want To post an event directly to another user's calendar with jamesiarmes/php-ews but in example i have find only how to make it with invitation.
I have admin account so i can write in athers user's post calendar directly.
i don't understant a lot because i'm new in ews so thx for any help.
// Replace this with your desired start/end times and guests.
$start = new DateTime('tomorrow 4:00pm');
$end = new DateTime('tomorrow 5:00pm');
$guests = array(
array(
'name' => 'Homer Simpson',
'email' => 'hsimpson#example.com',
),
array(
'name' => 'Marge Simpson',
'email' => 'msimpson#example.com',
),
);
// Set connection information.
$host = '';
$username = '';
$password = '';
$version = Client::VERSION_2016;
$client = new Client($host, $username, $password, $version);
// Build the request,
$request = new CreateItemType();
$request->SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType::SEND_ONLY_TO_ALL;
$request->Items = new NonEmptyArrayOfAllItemsType();
// Build the event to be added.
$event = new CalendarItemType();
$event->RequiredAttendees = new NonEmptyArrayOfAttendeesType();
$event->Start = $start->format('c');
$event->End = $end->format('c');
$event->Subject = 'EWS Test Event';
// Set the event body.
$event->Body = new BodyType();
$event->Body->_ = 'This is the event body';
$event->Body->BodyType = BodyTypeType::TEXT;
// Iterate over the guests, adding each as an attendee to the request.
foreach ($guests as $guest) {
$attendee = new AttendeeType();
$attendee->Mailbox = new EmailAddressType();
$attendee->Mailbox->EmailAddress = $guest['email'];
$attendee->Mailbox->Name = $guest['name'];
$attendee->Mailbox->RoutingType = RoutingType::SMTP;
$event->RequiredAttendees->Attendee[] = $attendee;
}
// Add the event to the request. You could add multiple events to create more
// than one in a single request.
$request->Items->CalendarItem[] = $event;
$response = $client->CreateItem($request);
// Iterate over the results, printing any error messages or event ids.
$response_messages = $response->ResponseMessages->CreateItemResponseMessage;
foreach ($response_messages as $response_message) {
// Make sure the request succeeded.
if ($response_message->ResponseClass != ResponseClassType::SUCCESS) {
$code = $response_message->ResponseCode;
$message = $response_message->MessageText;
fwrite(STDERR, "Event failed to create with \"$code: $message\"\n");
continue;
}
// Iterate over the created events, printing the id for each.
foreach ($response_message->Items->CalendarItem as $item) {
$id = $item->ItemId->Id;
fwrite(STDOUT, "Created event $id\n");
}
}
You define the attendees but miss the account where you want to create the event in:add this code before the $response
...
$request->Items->CalendarItem[] = $event;
//following lines are missing
$lsEmail = 'some#email.de';
$request->SavedItemFolderId = new TargetFolderIdType();
$request->SavedItemFolderId->DistinguishedFolderId = new DistinguishedFolderIdType();
$request->SavedItemFolderId->DistinguishedFolderId->Id = self::DISTINGUISHED_FOLDER_ID;
$request->SavedItemFolderId->DistinguishedFolderId->Mailbox = new EmailAddressType();
$request->SavedItemFolderId->DistinguishedFolderId->Mailbox->EmailAddress = $lsEmail;
// here your code continues
$response = $client->CreateItem($request);
...

Processing multi-step form in Laravel

I am quite new to laravel I have to insert many form fields in database so I divided the fields into multiple sections what I want to achieve is to store data of each section when user clicks next button and step changes and when user clicks previous button and makes some changes the database should be updated and if user leaves the form incomplete then when he logins next time form fill should fill up from the step he left in, till now i have successfully achieved to change steps and in first step 1 inserted the data into database and for other step i updated the database but I am having trouble if user comes to first step and again changes the forms fields how to update again first step data i am using ajax to send data and steps number
My Controller
function saveJobPostFirstStage(Request $request)
{
$currentEmployer = Auth::guard('employer')->user();
//$data['currentEmployer'] = $currentEmployer;
$employer_id = $currentEmployer->id;
$random = $this->generateRandomString();
$jobOne = new Job();
//Session::pull('insertedId');
if ($request->ajax()) {
try {
$stepPost = $request->all();
$step = $stepPost['stepNo'];
$insertedId = $stepPost['insertedId'];
switch ($step) {
case '1':
if ($insertedId == 0) {
$jobOne->employer_id = $employer_id;
$jobOne->job_title = $stepPost['jobTitle'];
$jobOne->company_id = (int)$stepPost['companyName'];
$jobOne->country_id = (int)$stepPost['country'];
$jobOne->state_id = (int)$stepPost['state'];
$jobOne->city_id = (int)$stepPost['city'];
$jobOne->street_address = $stepPost['street'];
$jobOne->job_code = $random;
$stepOne = $jobOne->save();
if ($stepOne) {
Session::put('insertedId',$jobOne->id);
//session(['insertedId'=>$jobOne->id]);
$success = ['success' => "Success",
'insertedId' => $jobOne->id];
//return json_encode($success);
}
}
else
{
$jobOne->employer_id = $employer_id;
$jobOne->job_title = $stepPost['jobTitle'];
$jobOne->company_id = (int)$stepPost['companyName'];
$jobOne->country_id = (int)$stepPost['country'];
$jobOne->state_id = (int)$stepPost['state'];
$jobOne->city_id = (int)$stepPost['city'];
$jobOne->street_address = $stepPost['street'];
$jobOne->job_code = $random;
$stepOne = $jobOne->whereId($insertedId)->update(['employer_id'=>$jobOne->employer_id,'job_title'=>$jobOne->job_title,'company_id'=> $jobOne->company_id,'state_id'=>$jobOne->state_id,'country_id'=>$jobOne->country_id,'city_id'=>$jobOne->city_id,'street_address'=>$jobOne->street_address,'job_code'=>$jobOne->job_code = $random]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
}
break;
case '2':
$jobOne->employment_type_id = (int)($stepPost['employmentType']);
$jobOne->job_type_id = (int)($stepPost['jobType']);
$jobOne->job_level_id = (int)($stepPost['jobLevel']);
$jobOne->industry_type_id = (int)($stepPost['industryType']);
$jobOne->job_category_id = (int)($stepPost['jobCategory']);
//$jobOne->salary = $stepPost['jobSalaryRange'];
$jobOne->salary_period_id = (int)$stepPost['salaryPeriod'];
//$jobOne->vacancy_end_date = $stepOne['applicationDeadline'];
$stepOne = $jobOne->whereId($insertedId)->update(['employment_type_id'=> $jobOne->employment_type_id,'job_type_id'=>$jobOne->job_type_id,'job_level_id'=> $jobOne->job_level_id,'industry_type_id'=>$jobOne->industry_type_id,'job_category_id'=>$jobOne->job_category_id,'salary_period_id'=>$jobOne->salary_period_id]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
break;
case '3':
$jobOne->job_description = $stepPost['jobDescription'];
$jobOne->job_specification = $stepPost['jobSpecifications'];
$jobOne->job_responsibilities = $stepPost['jobResponsibilities'];
$stepOne = $jobOne->whereId($insertedId)->update(['job_description'=>$jobOne->job_description,'job_specification'=>$jobOne->job_specification,'job_responsibilities'=>$jobOne->job_responsibilities]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
default:
# code...
break;
}
return json_encode($stepPost);
//$this->alertMessage = 'Your Phone has been added Successfully.';
//$this->alertType = 'success';
} catch (QueryException $e) {
return $e->getMessage();
}
/* return redirect()->route('employer-account-page')
->with([
'alertMessage' => $this->alertMessage,
'alertType' => $this->alertType
]);*/
// $stepPost = Input::all();
}
/*$stepOne = $request->all();
$country_Id = (int)$stepOne['country'];
return json_encode((getType($country_Id)));*/
}
First of, your code is messy.
You should have a single table per form where each form have it's parent id.
The next step to refactor the code would be to create a single controler per form (you don't need it, but you want this)
Each form (a model) should have a method that recalculates the values of itself based on other forms, so that if you change a first form, then you can call the method that recalculates the second form, then call method of second form that recalculates the third form, etc.
This interface could be helpful
interface IForm {
public function getPreviousForm() : ?IForm; // These notations are since PHP7.1
public function recalculate() : void;
public function getNextForm() : ?IForm;
}
A simple code how it should work in practice
$formX->save();
$formX->getNextForm()->recalculate(); // This will call formX->recalculate(); formX+1->getNextForm()->recalculate()
// which will call formX+1->recalculate(); formX+2->getNextForm()->recalculate()
// etc...
// while getNextForm() != null
You may also need this if you would need to insert another form in the middle of the chain.
Hope it helps

Accessing variable yet to be created

I'm having some trouble here V_shop_menu $order_uuid is not populating. Now I'm guessing this is because its yet to be created this is done further below. The problem I have is there are 2 statements here doing inserts to tables but they both rely on each other.
I have a bit of chicken and egg situation as I need $shop_menu_uuid from the top area to complete the bottom insert. I was led to believe that as they are in the same public function it would just work but this is not the case.
What do I need to do to make this happen?
Thanks!
public function add_shopmenu(){
$postData = $this->input->post();
$condition['conditions'][] = "site_name ='".$this->sessionInfo['site']."'";
$site = $this->frontguide_Model->selectSingleRow("t_place",$condition);
$site_uuid = $site['site_uuid'];
unset($condition);
$condition['conditions'][] = "site_uuid ='".$site['site_uuid']."'";
$condition['conditions'][] = "shop_menu_name ='".$postData['shop_menu_name']."'";
$shopmenu_name = $this->frontguide_Model->selectData("v_shop_menus",$condition);
unset($condition);
$condition['conditions'][] = "site_uuid ='".$site['site_uuid']."'";
$shopmenus = $this->frontguide_Model->selectData("v_shop_menus",$condition);
$shop_menu_enabled = (isset($postData['shop_menu_enabled']))?$postData['shop_menu_enabled']:"false";
$shop_menu_uuid = $this->frontguide_functions->uuid();
$v_shop_menu= array(
"shop_menu_uuid" =>$shop_menu_uuid,
"site_uuid" =>$site_uuid,
"order_uuid" =>$order_uuid,
"shop_menu_extension" =>$shop_menu_extension,
"shop_menu_name" =>$postData['shop_menu_name'],
"shop_menu_greet_long" =>$postData['shop_menu_greet_long'],
"shop_menu_greet_short" =>$postData['shop_menu_greet_short'],
"shop_menu_timeout" =>$postData['shop_menu_timeout'],
"shop_menu_enabled" => $shop_menu_enabled,
"shop_menu_cid_prefix"=>$postData['shop_menu_cid_prefix']
);
log_message('debug',print_r($v_shop_menu,TRUE));
$vgu_response = $this->frontguide_Model->insert("v_shop_menus",$v_shop_menu);
$shop_menu_option_digits = $postData['shop_menu_option_digits'];
$shop_menu_option_order = $postData['shop_menu_option_order'];
$shop_menu_option_description = $postData['shop_menu_option_description'];
$shop_menu_option_param = $postData['shop_menu_option_param'];
for($i=0;$i<count($shop_menu_option_digits);$i++){
$option = array();
$option['shop_menu_option_digits'] = $shop_menu_option_digits[$i];
$option['shop_menu_option_order'] = $shop_menu_option_order[$i];
$option['shop_menu_option_description'] = $shop_menu_option_description[$i];
$option['shop_menu_option_param'] = $shop_menu_option_param[$i];
$shop_menu_option_uuid= $this->frontguide_functions->uuid();
$option['shop_menu_option_uuid'] = $shop_menu_option_uuid;
$option['shop_menu_uuid'] = $shop_menu_uuid;
$option['site_uuid'] = $site_uuid;
$vgu_response = $this->frontguide_Model->insert("v_shop_menu_options",$option);
}
$order_uuid = $this->frontguide_functions->uuid();
$order_data = array(
"site_uuid"=>$site_uuid,
"order_uuid"=>$order_uuid,
“offer_uuid" => "a6788e9b-67bc-bd1b-df59-ggg5d51289ab",
"order_context"=>$site['site_name'],
"order_name" =>$postData['shop_menu_name'],
"order_number" =>$shop_menu_extension,
"order_continue" =>'true',
"order_order" =>'333',
"order_enabled" =>"true",
);
$v_orders = $this->frontguide_Model->insert("v_orders",$order_data);
Now I'm guessing this is because its yet to be created this is done
further below.
Yes you are right.
It is quite simple.
Insert v_shop_menus data without $order_uuid .
after inserting in v_orders, get the $order_uuid and update the v_shop_menus using $shop_menu_uuid.

Cakephp update or add new record

I have an image upload that adds the filename to a table called attachments. If the id already exists then I want it to update and if not then create a new record. At the moment it creates a new record so I have multiple records forthe one id. The id's are from a table called Addon's.
I am not sure how to do this in cakephp.
if (!empty($this->data)) {
$this->layout = null;
//if(empty($this->data['AddOn']['id'])){unset($this->data['AddOn']);}
// restructure data for uploader plugin // NEED TO GET RID OF THIS ? MOVE IT
$tmp_file = $this->data['Attachment'][0]['file'];
$tmp_file['extension'] = array_reverse(explode('.', $tmp_file['name']));
$tmp_file['extension'] = $tmp_file['extension'][0];
$tmp_file['title'] = strtolower(substr($tmp_file['name'],0,(0-strlen('.'.$tmp_file['extension']))));
$this->data['Attachment'][0]['alternative'] = ucwords(str_replace('_',' ', $tmp_file['title']));
$previous = $this->AddOn->Attachment->find('first', array('conditions'=> array('model'=>'AddOn', 'foreign_key'=>$id)));
if( !empty( $previous ) ) {
$this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ];
}
if ($this->AddOn->save($this->data, array('validate' => 'first'))) {
$id = $this->AddOn->Attachment->getLastInsertID();
$att = $this->AddOn->Attachment->query("SELECT * from attachments WHERE id = ".$id);
$this->set('attachment',$att[0]['attachments']);
} else {
$tmp_file['name'] = 'INVALID FILE TYPE';
}
//debug($this->data);
$this->set('file', $tmp_file);
$this->RequestHandler->renderAs($this, 'ajax');
$this->render('../elements/ajax');
}
save() and saveAll() automatically update an existing row if the id has been set. You can do something like:
$previous = $this->AddOn->Attachment->find( /* whatever conditions you need */ );
if( !empty( $previous ) ) {
$this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ];
}
Now the old record will be updated if it exists.
As a side note, the code after a successful saveAll() doesn't make much sense: first you're saving data to the database, then immediately retrieving it again. You can just keep using $this->data that already has the same content.
And another side note: you should use query() only as a last resort when you can't use Cake's other methods. query("SELECT * from attachments WHERE id = ".$id) is a trivial case that can be rewritten as $this->Model->id = $id; $this->Model->read(); or using a simple $this->Model->find() query.

Categories