Delete record in patchentities in cakephp 3 - cakephp

Some rows which are related to employee are needed to be updated
User can update some record and delete some record in same form.
while doing patch entity list of records which is already present in table are fetched and stored in list object and it is patched with data which comes by request.
But only records are updated not deleted while doing patch entity.
$UserSkillsTable = \Cake\ORM\TableRegistry::get('UserSkills');
$list = $this->UserSkills
->find('ALL')
->contain(['MsSkills', 'MsSkills.MsSkillHeads', 'SkillLevels', 'RoSkillLevels'])
->where([
'UserSkills.emp_code' => $this->request->session()->read('user_emp_code'),
'approve_status' => 'P',
'UserSkills.is_active' => '1'
])
->toArray();
$userSkillEntities = $this->UserSkills->patchEntities(
$list,
$this->request->data['old_user_skill']
);

Related

Get last inserted ID after inserting to associated table

Employees table has a field named current_address_id. I'm adding a new address to Addresses like:
$updatedEntity = $this->patchEntity($employee, [
//some other fields
'user' => $userData,
'employees_phones' => $phonesData,
'employees_addresses' => $addressesData,
], [
'associated' => ['Users', 'EmployeesPhones', 'EmployeesAddresses']
]);
$this->save($updatedEntity);
I'm inserting the new address successfully but now I need to update Employees.current_address_id with the new address ID. How can I do this?
Table::save() returns the entity with updated ids. So store the return value in a variable and use appropriate property of the entity.
Try this one. It works for me.
$this->ModelName->save($updatedEntity);
$lastInsertedId = $updatedEntity->id;
The save method will update the entity with the last insert id as long as the entity id is not already set.

CakePHP: Save data in two models

In CakePHP I have two models: Clients & Tickets. A client can have many tickets and a ticket can only have 1 client.
When adding a new ticket I want to automatically create a new client by only entering a name. So the form would be:
Name = "Name client" >> Name should be save in Client table en new client_ID in Ticket table
Info = Ticket information >> Save in Ticket table.
"Save"
I'm not sure how this works. I have associations in the model and tried to saveAll but there is no data stored in the Client table. And how do I get the ID in the Ticket table?
Hope someone can point me in the right direction. I've searched for other answers but cant seem to find a solution. Is saveAll the right way to do this?
You should set a php condition before insert values into the table, the sql request 4 exemple return the numbers of repetition of the same ticket_id so if the returned value is greater than 1 the request can't execute else the request insert the values
The function to count number of rows : mysql_num_rows('request');
You can use the callback methods.
If you have defined your relation in the Ticket model with belongsTo Client, it will be accessible from that model.
public $belongsTo = array(
'Client' => array(
'className' => 'Client',
'foreignKey' => 'client_id',
),
);
So, if you want to make a new client before saving the ticket, you can do:
public function beforeSave ($options = array()) {
$this->data['Client']['name'] = $someVar;
$this->Client->save($this->data);
$this->data[$this->alias]['client_id'] = $this->Client->getInsertID();
return true;
}

Insert new row in wordpress table but delete all others

I'm trying to add a new row in a wordpress table (that i've created), but every times that i add the new row, all the others are deleted and if i look DB table i can see only last inserted row.
I've tried two methods, but i get the same results:
$ins_reply = $wpdb->insert( $table, array('itemid'=> $item_id, 'time' => $time, 'title' => '', 'text' => $content, 'author' => $user, 'deadline' => 0));
OR
$query_insert = "INSERT INTO ".$table." (`itemid` ,`time` ,`title` ,`text` ,`deadline` ,`author`) VALUES ('".$item_id."', '".$time."', '', '".$content."', '0', '".$user."')";
$wpdb->query($query_insert);
What's wrong in my code?
Your query as posted in your question is not the source of your issue.
Perhaps you are working on a plugin where the table creation script is accidentally wiping & re-installing the table during this operation?

CakePHP HABTM JoinTable w/Extra Field

So I have a customers table, a contacts table, and a contacts_customers join table, which also has contact_type_id field which maps to a contact_type table. I have used the information linked to from CakePHP update extra field on HABTM join table in an attempt to come up with a solution, but it's only partly working. I changed the add() method in the ContactCustomersController to
$this->ContactsCustomer->Contact->save($this->data);
$this->ContactsCustomer->create();
if ($this->ContactsCustomer->save($this->data,
array('validate' => 'first'))) {
$this->Session->setFlash(__('The contacts customer has been saved', true));
$this->redirect(array('controller' => 'contacts_customers', 'action' => 'index'));
} else {
$this->Session->setFlash(__('The contacts customer could not be saved. Please, try again.', true));
}
Note the two-part save; this is because using the saveAll() method of the ContactsCustomer model was just out and out failing with no indication of the problem (all that showed up in the SQL log on the resulting page was a BEGIN immediately followed by a ROLLBACK). My assumption here was that this was due to the foreign key constraint between the contacts table and the contacts_customers table, so I opted for the two-part save.
In any event, there are no errors reported in the current code, but the end result is that the appropriate information is saved in the contacts table, but nothing is saved in the contacts_customers join table. The data posted appears to be appropriate according to the FireBug log data:
_method POST
data[Contact][address_1] asdsad
data[Contact][address_2]
data[Contact][city] asdasd
data[Contact][email] jb#sc.net
data[Contact][fax]
data[Contact][first_name] Joe
data[Contact][last_name] Blow
data[Contact][mobile_phon...
data[Contact][office_phon... sdfsdfdf
data[Contact][postal_code... 121212
data[Contact][state] asdas
data[Contact][title]
data[ContactsCustomer][ContactType]
data[ContactsCustomer][ContactType][] 1
data[ContactsCustomer][ContactType][] 2
data[ContactsCustomer][ContactType][] 3
data[ContactsCustomer][Customer] 1
What have I done incorrectly here? Many thanks to any assistance offered!
Relevant model data:
contact.php
var $hasMany = array(
'ContactsCustomer'
);
contact_types.php
var $hasMany = array(
'ContactsCustomer'
);
customer.php
var $hasMany = array(
'ContactsCustomer'
);
contacts_customer.php
var $belongsTo = array(
'Contact', 'ContactType', 'Customer'
);
haven't tested that yet, but I believe $this->data might have been modified by the first save. Just use an extra variable to hold that data.

cakephp not saving update value to related table, but no errors

Update order function finds all orderlines of current order.
Loops through subtracting quantity ordered from stock level and holding new stock level value in $newstock. All good.
But won't save.
Echoes "success" and the correct value but the database is not updated.
The Order status field does update, with the same code syntax.
It also has the same relationships with the Orderline. (Function called from Orderline Controller)
The table relationships are:
'Product'hasMany = array('Orderline');
'Order' hasMany = array('Orderline');
'Orderline' belongsTo = array('Order', 'Product');
function updateOrder(){
$this->data['Order']['id'] = $this->getOrderid();
$orderproducts = $this->Orderline->find('all',array('conditions' =>
array('Orderline.order_id' => $this->data['Order']['id'])));
foreach($orderproducts as $orderproduct){
$newstock = $orderproduct['Product']['stock']-$orderproduct['Orderline']['quantity'];
$this->data['Product']['stock']= $newstock;
if( $this->Product->saveAll($this->data)){
echo "success" ;
}else{
echo "not saved";
}
}
$this->data['Order']['status']= 1;
$this->Order->saveall($this->data);
}
I want to add that I was running into silent save fails using saveAll because I hadn't cleared the APP/tmp/cache folder.
Solved.
It had actually been adding new rows to the Product table.
This line was missing from the insert in the foreach loop, reminding it to use the current Product id to know where to insert the new data.
$this->data['Product']['id']= $orderproduct['Product']['id'];

Resources