Custom model function to insert a new record in cakephp 3 - cakephp

I'm new to CakePHP. I have a table to keep record of user's activity by creating a log in it. The table has two columns
+----+------------+-----------+
| id | user_id | comment |
+----+------------+-----------+
I want to pass values from within controller like
$this->ActivityLogs->log($user_id, 'Message sent');
log is a custom function inside ActivityLogs model which will record some more data along with passed data
public function log($user_id = null, $message = null)
{
... record code goes here
return true;
}
But couldn't get how to write insert query inside model.
How can I create custom methods like this and also can anyone suggest me good resource to go through model queries and understanding.

public function log($user_id = null, $message = null){
//I assume here that your table name is 'logs'
$logsTable = \Cake\ORM\TableRegistry::get('Logs', array('table' => 'logs'));
$log = $logsTable->newEntity();
$log->user_id = $user_id;
$log->body = $message ;
if ($logsTable->save($log)) {
return true;
}
return false;
}

Related

Sorty by calculated field with active record yii2

I have threads and messages on thread
I want to return all threads with the last message time, so I added a new field like this on thread model
public function fields()
{
$fields= ['idThread', 'idUser', 'title', 'unread', 'username','lastMesageTime'];
return $fields;
}
now with this method I get the calculated value lastMessageTime
public function getLastMessageTime()
{
return $this->hasMany(Messages::className(), ['idThread' => 'idThread'])
->select('time')->orderBy('time DESC')->limit(1)->scalar();
}
on my index method using active record like this
return Thread::find()->select('idThread, title, idUser')->all();
this works and I get lastMessageTime with the right value, but I want to order by so I can get the thread with the most recent lastMessageTime the first one, I tried with the following code
public function scopes() {
return array(
'byOrden' => array('order' => 'lastTimeMessage DESC'),
);
}
any idea?
Edit:
this workaround works, but I think this is not a good way because I'm not using active record so fields like username that I had defined on Thread model I had to fetch it again
$query = (new \yii\db\Query());
$query->select('*, (SELECT max(time) as lastMessageTime from messages where messages.idThread = thread.idThread ) lastMessageTime,
(SELECT name from users where users.idUser = thread.idUser) as name ')
->from('threads')
->where(['idUser'=>$idUser])
->orderBy('lastMessageTime DESC');
$rows = $query->all();
return $rows;
You can define extra fields as model properties, then override find method to load data for them.
class Thread extends \yii\db\ActiveRecord
{
public $lastMessageTime;
public static function find()
{
$q = parent::find()
->select('*')
->addSelect(
new \yii\db\Expression(
'(SELECT max(time) FROM messages WHERE messages.idThread = thread.idThread) AS lastMessageTime'
);
return $q;
}
}
Then you can load and order models like this:
$rows = Thread::find()->orderBy(['lastMessageTime' => SORT_DESC])->all();

How to get model attribute name based on id using Spatie/Activitylog?

I'm trying to get Employee Name based on employee_id of Task model using attributes properties of Spatie/Activitylog activity_log table.
My model:
use LogsActivity;
protected $fillable = ['id','employee_id', 'name', 'description'......];
protected static $logAttributes = ['id','employee_id','name', 'description'......];
protected static $logFillable = true;
protected static $logUnguarded = true;
My controller:
{
$activity = Activity::orderBy('id', 'DESC')->paginate(15);
return view('adminlte::home', ['activity' => $activity]);
}
My blade:
#foreach($activity as $act)
{{$act->changes['attributes']['employee_id']}}
#endforeach
Records saved in properties field:
{"attributes":{"id":170,"employee_id":"[\"1\",\"2\"]","name":"test","description":"test",......}}
Also, in my blade the result is:
|employee_id | name | description| ...
|------------|------------|------------|--------
|["1","2"] | test | test | ....
The question is, how to get Name field based on employee_id. For example in this case, Jon, David(not their IDs(["1","2"]). So, I want to get Names instead of IDs.
Thank you in advance.
I would fetch them from the database
1) create a list of ids and fetch them.
$employees = Employee::whereIn('id', $activity->pluck('employee_id')->flatten())
->get()
->mapWithKeys(function ($employee) {
return [$employee->id => $employee];
});
2) Send it to the front-end
return view('adminlte::home', ['activity' => $activity, 'employees' => $employees]);
3) Use the mapping to display names
#foreach($activity as $act)
#foreach($act->changes['attributes']['employee_id'] as $employeeId)
{{ $employees[$employeeId] }},
#endforeach
#endforeach

cakephp code to insert values from forloop in different rows

i am submitting the location from textbox and putting values in comma seprated form like ngp,akola,kanpur.
Now i want if i have 3 values in location textbox then it insert 3 rows in location table one for ngp,second for akola and third for kanpur.
but it also takes last inserted id of user table and post all values in location table.
my location table have fields id,name,user_id.
in user_id column i need the last inserted id of user table and in name column i need to insert all values in table..
please help me to do this..below is my code.
function add() {
if (!empty($this->request->data)) {
$this->User->set($this->data['User']);
$isValidated = $this->User->validates();
if ($isValidated) {
// Generating UUID
if (!empty($this->request->data['User']['company_name'])) {
$this->request->data['User']['is_business'] = 1;
}
if ($this->User->save($this->request->data, array('validate' => false))) {
$lastId = $this->User->id;
$location = implode(',',$this->request->data['User']['location']);
for(i=1;i<=$location;i++){
$this->Location->save($location);
}
}
}
}
}
$lastId = $this->User->id;
$location = explode(',',$this->request->data['User']['location']);
foreach($location as $value){
$data = array();
$data["name"] = $value;
$data["user_id"] = $lastId;
$this->Location->save($data,false);
$this->Location->id = false;
}
Model::saveAll(array $data = null, array $options = array())
$this->request->data['Location'] = explode(',',$this->request->data['User']['location']);
if ($this->User->saveAll($this->request->data, array('validate' => false))){ // ...}

CakePHP 3 : display data from other model and pass parameter in url from action

I'm working on a project using CakePHP 3.x.
I have UserAddress, ServiceRequests, Service models.
There is a button on service/view/$id which when clicked will ask user to select address from service-requests/serviceArea which has a list of addresses added by user. service-requests/serviceArea view will contain a select button which when clicked will call add action in ServiceRequests controller with passing two parameters serviceId and userAddressId
This is the serviceArea function created by me.
public function serviceArea($id = null)
{
public $uses = array('UserAddress');
$service = $id;
$query = $userAddresses->find('all')
->where(['UserAddresses.user_id =' => $this->Auth->user('id')]);
$this->set(compact('userAddresses'));
$this->set('_serialize', ['userAddresses']);
}
How to display the address and also pass the $service parameter to the serviceArea view.
I am new to CakePHP, so if you think question is incomplete any edit to it will be appreciated instead of down-voting.
Thank You.
Edit 2
Thank for your answer #jazzcat
After changing my code according to yours and visiting http://domain.com/service-requests/service-area/$id. It is showing error as
Record not found in table "service_requests"
and pointing to the ServiceRequestsController on line no 33
The ServiceRequestController as containing line no 33 is
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* ServiceRequests Controller
*
* #property \App\Model\Table\ServiceRequestsTable $ServiceRequests
*/
class ServiceRequestsController extends AppController
{
/**
* isAuthorized method
*
*/
public function isAuthorized($user)
{
$action = $this->request->params['action'];
// The add and index actions are always allowed.
if(in_array($action, ['index', 'add', 'serviceRequests'])) {
return true;
}
// All other actions require an id.
if (empty($this->request->params['pass'][0])) {
return false;
}
// Check that the service request belongs to the current user.
$id = $this->request->params['pass'][0];
$serviceRequest = $this->ServiceRequests->get($id); // line : 33
if($serviceRequest->user_id == $user['id']) {
return true;
}
return parent::isAuthorized($user);
}
/* Other actions */
}
?>
This worked for me.
Just added the serviceArea action name in the isAuthorized method
if(in_array($action, ['index', 'add', 'serviceArea'])) {
return true;
}
and it's working fine as expected.
There is alot wrong with your code. Please read the docs
Is the table named user_addresses or user_address ?
You seem to mix the both.
The following would be the correct way to do it assuming your table is named user_addresses
public function serviceArea($id = null)
{
$this->loadModel('UserAddresses');
$userAddresses = $this->UserAddresses->find('all')
->where(['UserAddresses.user_id =' => $this->Auth->user('id')]);
// If you want to filter on the serviceArea ID aswell
if($id)
$userAddresses->andWhere(['id' => $id]);
// Setting SerivceArea ID to compact makes it available in view.
$serviceAreaId = $id;
$this->set(compact('userAddresses', 'serviceAreaId'));
$this->set('_serialize', ['userAddresses']);
}
This snippet:
$id = $this->request->params['pass'][0];
$serviceRequest = $this->ServiceRequests->get($id); // line : 33
Just checks if the first parameter passed to the method exists in ServiceRequests.
(That parameter could be anything, you have to keep that in mind when creating all your methods in that controller, that is to say the least.. bad)
I'm assuming that the service_requests table is associated with the users table and an user_id column exists in the service_requests table.
If that is the case this should work:
public function isAuthorized($user)
{
$action = $this->request->params['action'];
// The add and index actions are always allowed.
if(in_array($action, ['index', 'add'])) {
return true;
}
// Is not authorized if an argument is not passed to the method.
// Don't know why you'd want this , but sure.
if (empty($this->request->params['pass'][0])) {
return false;
}
// Check that the service request belongs to the current user.
$user_id = $this->Auth->user('id');
$serviceRequest = $this->ServiceRequests->find()->where(['ServiceRequests.user_id' => $user_id])->first();
if(!empty($serviceRequest)) {
return true;
}
return parent::isAuthorized($user);
}

Add wordpress custom post type data to an external db

This function adds custom post 'event' data into a Salesforce db. I've tested the function outside of Wordpress and it works flawlessly. When I test it inside Wordpress by adding a new event, no error is generated and a the data is not inserted into the SF db. I've also tested this by printing out the $_POST and saw that the data is being collected. How can I get this display some errors so that I can trouble shoot this?
function add_campaign_to_SF( $post_id) {
global $SF_USERNAME;
global $SF_PASSWORD;
if ('event' == $_POST['post-type']) {
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(CD_PLUGIN_PATH . 'Toolkit/soapclient/enterprise.wsdl.xml');
$mySFlogin = $mySforceConnection->login($SF_USERNAME, $SF_PASSWORD);
$sObject = new stdclass();
$sObject->Name = get_the_title( $post_id );
$sObject->StartDate = date("Y-m-d", strtotime($_POST["events_startdate"]));
$sObject->EndDate = date("Y-m-d", strtotime($_POST["events_enddate"]));
$sObject->IsActive = '1';
$createResponse = $mySforceConnection->create(array($sObject), 'Campaign');
$ids = array();
foreach ($createResponse as $createResult) {
error_log($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
error_log($mySforceConnection->getLastRequest());
error_log($e->faultstring);
die;
}
}
}
add_action( 'save_post', 'add_campaign_to_SF');
I would use get_post_type() to check for "event" posts. Use error_log() to write to the PHP error log for additional debugging - check the status of your Salesforce login, etc.
Keep in mind that save_post will run every time a post is saved - created or updated - so you might want to do some additional checking (like setting a meta value) before creating a new Campaign in Salesforce, otherwise you will end up with duplicates.
function add_campaign_to_SF( $post_id ) {
$debug = true;
if ($debug) error_log("Running save_post function add_campaign_to_SF( $post_id )");
if ( 'event' == get_post_type( $post_id ) ){
if ($debug) error_log("The post type is 'event'");
if ( false === get_post_meta( $post_id, 'sfdc_id', true ) ){
if ($debug) error_log("There is no meta value for 'sfdc_id'");
// add to Salesforce, get back the ID of the new Campaign object
if ($debug) error_log("The new object ID is $sfdc_id");
update_post_meta( $post_id, 'sfdc_id', $sfdc_id );
}
}
}
add_action( 'save_post', 'add_campaign_to_SF' );

Resources