Can't delete row from beforeSave method in CakePHP 2.4+ - cakephp-2.0

I cant delete in my beforeSave() method in newer version of Cake but it works with earler libs (e.g. version 2.2)
Does anyone know how get it working again without altering the Cake libs?
Code:
public function beforeSave($options = array()) {
if(!empty($this->data['Attachment']['delete']) && (int) $this->data['Attachment']['delete'] === 1) {
if($this->deleteFromDb((int) $this->data['Attachment']['id'])) {
$this->data['Attachment'] = array();
return true;
} else {
return false;
}
}
return true;
}
public function deleteFromDb($id) {
if ($this->delete($id)) {
return true;
} else {
return false;
}
}
The following line returns false but I don't understand why:
if($this->deleteFromDb((int) $this->data['Attachment']['id']))
If I replace it with the following it is still returns false:
if($this->delete((int) $this->data['Attachment']['id']))
If I access the method from a controller it returns true, e.g.
$this->Model->deleteFromDb($id);
Any help at all would be great.

I got this resolved, In the newer libs for cake you can't delete from beforeSave(), so I moved it to the next appropriate method, in my case this was beforeValidate().
Hope this helps someone.

Related

Function Download in Yii2

public function actionUnduh($id) {
$download = PstkIdentifikasi::findOne($id);
$path = Yii::getAlias('../web/bukti/') . $download->bukti;
if (file_exists($path)) {
//return \Yii::$app->response->sendFile($download->pre_paper,#file_get_contents($path));
return Yii::$app->response->sendFile($path);
}
}
I need to download file from folder web/bukti, the code not error but the code doesn't work, Anyone can help me :(
public function actionUnduh($id)
{
$download = PstkIdentifikasi::findOne($id);
$path = Yii::getAlias('#webroot').'/bukti/'.$download->bukti;
if (file_exists($path)) {
return Yii::$app->response->sendFile($path, 'File name here');
}
}
Refer below:
Yii2 Aliases
Yii2 sendFile()
Firstly you can write an action in SiteController.php like this:
public function actionDownload()
{
$file=Yii::$app->request->get('file');
$path=Yii::$app->request->get('path');
$root=Yii::getAlias('#webroot').$path.$file;
if (file_exists($root)) {
return Yii::$app->response->sendFile($root);
} else {
throw new \yii\web\NotFoundHttpException("{$file} is not found!");
}
}
then you can call this function anywhere:
Yii::$app->urlManager->createUrl(['site/download','path'=>'/upload/files/','file'=>'filename.pdf'])
Be careful your files must be in this directory:
"backend/web/upload/files/filename.pdf"
or
"frontend/web/upload/files/filename.pdf"

Cakephp 3 : How to detect mobile in controller by requestHandler?

I need detect mobile in controller for a condition. I have tried below code in my controller.
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
Then I have written below code in index method
if ($this->RequestHandler->is('mobile'))
{
//condition 1
}else {
//condition 2
}
Here I get the error
Error: Call to undefined method Cake\Controller\Component\RequestHandlerComponent::is()
How can mobile detect in controller ?
The request handler isn't necessary for that since all the request handler does is proxy the request object:
public function isMobile()
{
$request = $this->request;
return $request->is('mobile') || $this->accepts('wap');
}
The controller also has direct access to the request object, so the code in the question can be rewritten as:
/* Not necessary
public function initialize()
{
parent::initialize();
}
*/
public function example()
{
if ($this->request->is('mobile')) {
...
} else {
...
}
}
I think that will be
$this->RequestHandler->isMobile()
CakePHP 3 uses mobiledetect/mobiledetectlib lib
In bootstrap.php added 2 types of detection 'mobile', 'tablet'
You can use it:
if ($this->request->is('mobile')) {
// ...
}
elseif ($this->request->is('tablet')) {
// ...
}
else {
// ...
}

How to ensure only one record is active

I want that when a record is saved and marked as active, all other records are marked INactive.
I've tried the following code in my model:
public function beforeSave($options = array()) {
if (!empty($this->data['Ticket']['is_active'])) {
$this->data['Ticket']['is_active'] = 0;
}
return true;
}
However this code is error
Use afterSave
Instead of using beforeSave, it's more appropriate to use afterSave, and updateAll like so:
public function afterSave($created) {
if (!empty($this->data[$this->alias]['is_active'])) {
$this->updateAll(
array('is_active' => 0),
array(
'id !=' => $this->id,
'is_active' => 1
)
);
}
}
I.e. after successfully saving a record, if it is active disable all the others.
Note: be sure to use the same method signature as the parent class. It varies depending on which version of CakePHP you are using.
You can write before save method like
public function beforeSave($options=array()){
if (!empty($this->data[$this->alias]['is_active'])) {
$this->data[$this->alias]['is_active'] = 0;
}
return true;
}

cakephp render + afterfilter variables are unset

I am trying to use render for specific action names in my app.
Actually, here are my condition set in my AppController::afterFilter()
if($this->action == 'parameter') {
$this->render('/Elements/parameter');
}
else if($this->action == 'datagrid') {
$this->render('/Elements/datagrid');
}
And in my controller /samples/parameter :
$this->set('model', Inflector::singularize(Inflector::camelize($this->name)));
$this->set('controller', $this->name);
if($parameter_id) {
$this->set('mode', $mode);
$this->set('parameter', $this->Sample->find('first', array('conditions' => array('Sample.id' => $parameter_id))));
} else {
$this->set('mode', 'add');
$this->set('parameter', array());
}
I know that I have to render AFTER the definition of variables, so I use afterFilter Something I don't understand or missed ?
Infos:
I have set in Samples Controller the function
public function afterFilter(){
parent::afterFilter();
}
Thank you all!
The afterFilter() callback is called after rendering process is done, so calling render() inside it is doing it wrong.
If you want to change the view to be rendered do so in beforeRender(). So do something like
if ($this->action == 'parameter') {
$this->view = '/Elements/parameter';
} elseif ($this->action == 'datagrid') {
$this->view = '/Elements/datagrid';
}

CakePHP - How to check in beforeSave if it's an INSERT or UPDATE

In my model's beforeSave method, how can I check if the save operation is going to be an INSERT or an UPDATE?
I want to add to the model data, but only if it's inserting a new row.
You can just check in the data if the id exists:
function beforeSave($options = array())
{
if(empty($this->data[$this->alias]['id']))
{
//INSERT
}
else
{
//UPDATE
}
}
This is how you would do in Cakephp 4 (in case someone is looking for it)
EDIT it also applies to Cakephp 3 as BadHorsie stated
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
{
if ($entity->isNew()) {
//INSERT
}else{
//UPDATE
}
}
You can try this
public function beforeSave($options = array()) {
if($this->id) {
// Update
} else {
// Add
}
}

Resources