CakePHP change view for action in plugin - cakephp

I'm developing a plugin that has an action which decide the view to render according to data properties:
example:
class ProfilesController extends MyPluginAppController {
public function myaction($id){
//..omitting checks..
$profile = $this->Profile->read(null,$id);
//Stuff
if($this->hasDedicatedViewFor($profile)){
$this->render('profiles'.DS.$this->getDedicatedViewFor($profile));
}
//Else render default action view
}
}
While this controller was inside the APP everything was working right,
after moving into Plugin, cake says:
Error: Confirm you have created the file:
.../app/View/Plugin/MyPlugin/Profiles/myaction_secondary.ctp
While I'd expect to load it from:
.../plugins/MyPlugin/View/Profiles/myaction_secondary.ctp

While I'd expect to load it from:
.../plugins/MyPlugin/View/Profiles/myaction_secondary.ctp
It is attempting to load the default plugin path
If you trace through the code for finding template files it is checking multiple paths for plugin view files:
$paths = $this->_paths($plugin);
$exts = $this->_getExtensions();
foreach ($exts as $ext) {
foreach ($paths as $path) {
if (file_exists($path . $name . $ext)) {
return $path . $name . $ext;
}
}
}
The path in the error message is the last place CakePHP looks for a plugin view path, but it should also be checking the plugins directory. Debug the above code to see where CakePHP is looking for files if in doubt.
The path being wrong in the error message probably indicates using an out of date version of CakePHP; it's always, always a good idea to maintain your applications running the most recent maintenance release for the major version you are using. From the info provided that's 2.7.3 at the time of this answer.

Related

Check if event is coming from a model inside a plugin?

I need all models inside a custom CakePHP plugin to use a database prefix. I'm trying to use an event, as suggested by #lorenzo.
EventManager::instance()->on('Model.initialize', function ($event) {
$instance = $event->subject();
$instance->table('prefix_' . $instance->table());
});
I'm getting several callbacks from my plugin model as well as DebugKit models, and potentially it could be other models in the application.
Is there a way to tell if a given $event is coming from within a plugin?
I have checked $event->getSubject() and it contains the corresponding Table class. The only feasible way I could come up with is to check some properties for the plugin name.
$event->getSubject()->getRegistryAlias() is ExamplePlugin.Posts
$event->getSubject()->getEntityClass() is ExamplePlugin\Model\Entity\Post
I could check if either starts with ExamplePlugin. Is there a better way?
The fact that basically any PHP namespace can be a plugin means you could do something like that:
EventManager::instance()->on('Model.initialize', function (\Cake\Event\EventInterface $event) {
/** #var \Cake\ORM\Table $object */
$object = $event->getSubject();
$tableClassName = get_class($object);
$isApp = str_starts_with($tableClassName, 'App');
});
Because your main app's namespace will always begin with App
This of course wouldn't distinguish between your private plugins which are located in plugins and plugins which are installed via composer and therefore live in the vendor directory.
But you could introduce a name prefix to all your private plugins so you can easily distinguish them from any other plugins.

Error download file PDF in Yii2: Unknown Method

I want to download file PDF from frontend/web/uploads. And I have an error in the controller (maybe):
Calling unknown method: frontend\controllers\BukuController::findModel()
This is my source code:
BukuController.php
public function actionDownload($id)
{
$model = $this->findModel($id);
$file ='../frontend/uploads/'.$model->file_buku;
if(file_exists($file))
{
return Yii::$app->response->sendFile($file);
exit;
}
}
And this is function in views, views/buku/index.php:
<?= Html::a('Download', ['download','id'=> $buku->file_buku]); ?>
(Solved)
As the error state, you missing in your BukuController method called findModel.
This method should search the model in the DB.
Something like this:
protected function findModel($id)
{
if (!is_null($model = Buku::findOne($id))) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
Of course if your model is not Buku, you need to change it relatively, and also import it in the top of the controller file:
use app\models\Buku; // Basic application.
use common\models\Buku; // Advanced application when models store in common folder.
use frontend\models\Buku; // Advanced application when models store in frontend folder.
Change $file variable to this.
$file =Yii::$app->getBasePath().'/web/uploads/'.$model->file_buku;

Cannot load PHPMailer 5.5 on CakePHP 2

In an unrelated, vanilla PHP project, I simply have this:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
It pulls in just fine. Following CakePHP 2.10's standards, I put all associated (composer'd) files in the app/Vendor folder and try this in my controller:
public function index($load = null) {
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include(APP . 'Vendor' . DS.'autoload.php');
I get:
syntax error, unexpected 'use' (T_USE)
Any attempts to move the use around end up not working, so I ignore them and try to get it to work without namespaces.
require_once(APP . 'Vendor' . DS.'autoload.php');
require_once(APP . 'Vendor' . DS.'phpmailer\phpmailer\src\PHPMailer.php');
I know it's loading the PHP file via require_once, and that file includes the PHPMailer class. I get this error:
Error: Class 'PHPMailer' not found
But I know that class has to be present somewhere, because I loaded it. Code looks like this, to call it:
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.zoho.com'; // Specify main and backup SMTP servers
etc. So I'm not sure if this version of PHPMailer refuses to work without namespaces, which CakePHP 2 doesn't support? All other questions on Google do not seem to help me.
You're putting the use statements in the wrong place; they need to go at the top of your file (after any namespace declaration) as they are not block-scoped. Read the PHP docs.
You can mix namespaced and non-namespaced code, you just need to be aware that it's going on.

Correct way in CakePHP 1.3 to create zip file and download without leaving view

I just upgraded from cakephp 1.1 to 1.3. I have everything on the site updated and working great, except for creating and downloading zip files.
Here is the code in my accounts_controller.php:
function zip() {
$this->checkSession();
$this->checkUpgradedAccount();
$files = array();
$this->layout="zip";
/*
code where I locate the files to zip, combine them, etc
*/
$tmp_file = "/home/[userdirectory]/tmp/".md5(mktime()).".zip"; //directory name edited
$command = "/usr/bin/zip -j $tmp_file ".implode(" ",$zip_files);
exec($command);
foreach($zip_files as $zf) {
unlink($zf);
}
$file_path = $tmp_file;
$this->set("path",$file_path);
$this->render();
}
When I call this action, however, I get an error:
Error: The requested address '/accounts/zip' was not found on this
server.
It worked just like this in version 1.1. I'm assuming something has changed, but I'm not sure what, and was unable to find anything pertinent in the documentation.
The zip.ctp view file does exists, but it has nothing in it other than: <?php ?>
I suspect something is different with layouts. There is NO "zip.ctp" in the /layouts directory. However, I have changed that line to $this->layout('default'); and it renders a blank page with NO ERROR, but also with no download.
Please direct me on the proper way to download my zip file in cake 1.3. Thanks in advance.
You have two different problems here. That error you're getting is because you don't have a zip layout file. As for your problem with getting the zip file, you should be using the media view class - http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Views.html#media-views

Integrating a file browser into ckeditor & CakePHP

recently found an article in http://hashtwo.com/blog/integrating-a-file-browser-into-ckeditor-cakephp to integrate a file browser into ckeditor (file manager of core five labs )
I followed the steps but i get an error when I click the browse server button,
Missing Controller:
Error: CkeditorController could not be found.
I had the same error at some point during my setup, but I don't seem to recall what was it and how I fixed it. Let me know if my next solution does not fix your problem and I will investigate a little more:
First I followed the following tutorial which worked well, but missed the Authentication part: http://labs.corefive.com/projects/filemanager/
Then I used the tutorial you referenced, except for the last section of code provided. Instead I added the following code directly to my view page: admin_add.ctp
<?php echo $form->textarea('body', array(/*'class'=>'ckeditor', */'id' => 'body', 'class' => 'body')) ?>
<?php
include_once 'ckeditor/ckeditor.php' ;
//require_once 'ckfinder/ckfinder.php' ;
//$initialValue = 'Default value goes here' ;
$ckeditor = new CKEditor() ;
$ckeditor->basePath = '/ckeditor/' ;
$ckeditor->config['filebrowserBrowseUrl'] = '/ckeditor/filemanager/index.html';
$ckeditor->config['filebrowserUploadUrl'] = '/ckeditor/filemanager/connectors/php/filemanager.php';
$ckeditor->config['filebrowserImageBrowseUrl'] = '/ckeditor/filemanager/index.html?type=Images';
$ckeditor->config['filebrowserImageUploadUrl'] = '/ckeditor/filemanager/connectors/php/filemanager.php?command=QuickUpload&type;=Images';
$ckeditor->config['filebrowserWindowWidth'] = '800';
//CKFinder::SetupCKEditor( $ckeditor,'/ckfinder/' ) ;
// This will replace CakePHP textarea listed above.
$ckeditor->replace('body');
?>
Also, for the Auth Section of his tutorial I changed it to match my requirements:
function auth() {
session_name("CAKEPHP");
session_start();
if(isset($_SESSION['Auth']['User']) )
{
//Since CKEditor for me is only used in the admin section
//I make sure only admins can access it, group_id=1
if($_SESSION['Auth']['User']['group_id'] == 1)
{
return true;
}
}
return false;
}
If it tries to find a controller this means it can not access the editors file or folder and instead the dispatcher of CakePHP gets the request and tries to load a fckeditor controller.
This means you'll need to place the editor in the right directory (for example app/webroot/fckedtor/) or use the correct url to access it.

Resources