i create my component like this
<?php
class UtilComponent extends Object
{
function strip_and_clean( $id, $array) {
$id = intval($id);
if( $id < 0 || $id >= count($array) ) {
$id = 0;
}
return $id;
}
}
and use it like this
var $name = 'Books';
var $uses = array();
var $components = array('Util');
public function index($id = 0){
$this -> set('page_heading','Packt Book Store');
$book=array(
'0'=>array(
'bookTitle' =>'Object Oriented Programming with PHP5',
'author' =>'Hasin Hayder',
'isbn' => '1847192564',
'releaseDate' => 'December 2007'
),
'1'=>array(
'bookTitle' =>'Building Websites with Joomla! v1.0',
'author' =>'Hagen Graf',
'isbn' => '1904811949',
'releaseDate' => 'March 2006'
),
);
$id = $this->Util->strip_and_clean( $id, $book);
$this->set('book',$book[$id]);
$this->pageTitle='Welcome to the Packt Book Store!';
}
but i got this error
**call_user_func_array() expects parameter 1 to be a valid callback, class 'UtilComponent' does not have a method 'initialize' [CORE\Cake\Utility\ObjectCollection.php, line 130]**
I believe a component should extend Component not Object:
class UtilComponent extends Component
{
}
The component will then inherit the initialize() method.
Got a similar issue.
Apart from the error message ... does not have a method 'initialize' ..., one more message was there ... does not have a method 'startup' ....
The issue was I created the component file inside the Controller directory instead of Controller/Component.
I also face same issue like
Warning (2): call_user_func_array() expects parameter 1 to be a valid callback, class 'ImageComponent' does not have a method 'initialize' [CORE\Cake\Utility\ObjectCollection.php, line 128]
Warning (2): call_user_func_array() expects parameter 1 to be a valid callback, class 'ImageComponent' does not have a method 'beforeRender' [CORE\Cake\Utility\ObjectCollection.php, line 128]
Warning (2): call_user_func_array() expects parameter 1 to be a valid callback, class 'ImageComponent' does not have a method 'shutdown' [CORE\Cake\Utility\ObjectCollection.php, line 128]
Solution is :
Add Image component into controller/component then
change class ImageComponent extends object { ... }
with class ImageComponent extends Component { ... }
Related
I have a problem where the value for the cookie I set is not being kept if switching to a different section (controller) with CakePHP3.
I establish the original cookie in the AppController so it is sitewide:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection;
class AppController extends Controller
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Cookie');
//set up initial cart cookie
$this->response = $this->response->withCookie(
(new Cookie('cart'))
->withPath('/')
->withValue(json_encode([]))
->withExpiry(new \DateTime('+1 month'))
);
}
I then have it set up in the CartController to add selected items to the cart cookie:
<?php
// src/Controller/CartController.php
namespace App\Controller;
use Cake\I18n\Time;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection;
class CartController extends AppController
{
public function index()
{
$cart = json_decode($this->request->getCookie('cart'));
$add_cart = ($this->request->getQuery('add') == null ? [] : $this->request->getQuery('add'));
if (count($add_cart) > 0) {
foreach($add_cart as $ac) {
if(!in_array($ac, $cart)) {
$cart[] = $ac;
}
}
}
//replace cookie
$this->response = $this->response->withCookie(
(new Cookie('cart'))
->withPath('/')
->withValue(json_encode($cart))
->withExpiry(new \DateTime('+1 month'))
);
$this->loadModel('Books');
$cart_items = [];
foreach($cart as $cartp) { //'contain' => ['BookTypes'],
$book = $this->Books->get($cartp, ['fields' => array('id','name','description')]);
$cart_items[] = $book;
}
$this->set(compact('cart_items'));
}
If I stay within "Cart", the cookie keeps the value. However, as soon as I move to any other page (home page or browsing books), the cookie value is reset to empty (an empty array).
What is causing this?
I found my problem.
Had to move the initial cookie from the initialize() to beforeFilter() in AppController.php and now it seems to be working.
MY first time creating a custom helper. I'm getting an error in my Controller Code that I"m calling a a method on a non existed object (helper). Yet i believe my helper "BM" is being loaded successfully because i'm not getting any errors on loading helpers.
Error: Call to a member function mcpGetActiveMerchantID() on a non-object
File: C:\wamp\www\bm\app\Controller\MCPController.php
Line: 412
I have placed BMHelper.php into my View\Helper\ directory.
<?php
class BMHelper extends AppHelper{
public function mcpGetActiveMerchant(){
return $this->Session->read('Auth.ActiveMerchant');
}
public function mcpGetActiveMerchantID() {
$activemerchant = $this->Session->read('Auth.ActiveMerchant');
foreach($activemerchant as $key => $value) {
$merchant_id = $key;
}
return $merchant_id;
}
}
?>
Then in my Controller I have this:
<?php
class MCPController extends AppController {
public $helpers = array('Html', 'Form', 'Session','BM','Js' => array('Jquery'));
public function walkinadd() {
$test = $this->BM->mcpGetActiveMerchantID(); //Line 412
}
}
?>
HEre is the error again (same as the error I pasted at the top)
Error: Call to a member function mcpGetActiveMerchantID() on a non-object
File: C:\wamp\www\bm\app\Controller\MCPController.php
Line: 412
Anyone know what is wrong?
Helpers are to be used in Views not Controllers, though you could do:
public function walkinadd() {
$view = new View($this);
$bm = $view->loadHelper('BM');
$test = $bm->mcpGetActiveMerchantID();
}
I try to do a contact form with Symfony 2.4.1. My form is a simple contact one without an entity.
The following error happens in my handler :
FatalErrorException: Error: Call to undefined method Symfony\Component\Form\Form::render() in C:\Program Files\wamp\www\sf2\src\Open\OpcBundle\Form\Handler\ContactHandler.php line 75
And the form handler code :
<?php
// src/Open/OpcBundle/Form/Handler/Handler.php
namespace Open\OpcBundle\Form\Handler;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
class ContactHandler {
protected $request;
protected $form;
protected $mailer;
public function __construct(Form $form, Request $request, $mailer) {
$this->form = $form;
$this->request = $request;
$this->mailer = $mailer;
}
public function process() {
if ('POST' == $this->request->getMethod()) {
$this->form->handleRequest($this->request);
$data = $this->form->getData();
$this->onSuccess($data);
return true;
}
return false;
}
protected function onSuccess($data) {
$message = \Swift_Message::newInstance()
->setContentType('text/html')
->setSubject($data['sujet'])
->setFrom($data['courriel'])
->setTo('me#gmail.com')
->setBody($this->render('OpcOpenBundle:Opc:Mails/contact.html.twig',
array('ip' => $request->getClientIp(),
'nom' => $data['nom'],
'msg' => $data['msg'])
)
);
$this->get('mailer')->send($message);
$request->getSession()->getFlash()->add('success', 'Your email has been sent! Thanks!');
return $this->redirect($this->generateUrl('contact'));
}
}
So the problem is that I don't have an object/instance for the renderView() method to call the template mail with setBody in the function onSuccess()
Which object/instance should I use for ?
Thanks
PS: sorry for my english, i'm French!
It's Symfony\Bundle\TwigBundle\TwigEngine class. service name is 'templating'.
BTW, why is you handler is not service?
TagController
public function view($id = null) {
if ($this->request->data != null) {
$this->Common->replyarticleAdd($this);
}
}
CommonComponent
/*
App::uses('Link', 'Model');
App::uses('User', 'Model');
App::uses('AppController', 'Controller');*/
I think , I should write it and it loads model but not effect.
ClassRegistry::init('Article');
App::uses('Article', 'Model');
ClassRegistry::init('Article');
App::uses('Article', 'Model');
class CommonComponent extends Component {
var $uses = array('Article');
public function replyarticleAdd($that = null) { // $this error can not re-assign.
debug($that->request->params['pass'][0]);
if ($that->request->params['pass'][0] != null) {
$this->Article->create(); // that is no effect
Error Call to a member function create() on a non-object
File: G:\pleiades\xampp\htdocs\cakephp\app\Controller\Component\CommonComponent.php
Line: 13 = $this->Article->create();
In controller create is ok but in component it cant. How can I do this?
In the component, try to work with the models this way:
App::uses('Article', 'Model');
$Article = new Article();
$Article->create();
Components do not have the $uses property, like controllers.
You can also use:
$Article = ClassRegistry::init('Article');
$Article->create();
Fairly experienced programmer but new to CakePHP 2.1 and spending my day struggling to get a custom Helper to work in View by following the manual: http://book.cakephp.org/2.0/en/views/helpers.html
I've not been able to find an answer and would greatly appreciate any Cake expertise.
My helper file in app/Helper/EntriesHelper.php:
App::uses('AppHelper', 'View/Helper');
class EntriesHelper extends AppHelper {
public function __construct(View $view, $settings = array()) {
parent::__construct($view, $settings);
}
public function spanWrapper($content) {
if(substr($content,0,1) == "#") {
return "<span class='label label-warning'>$content</span>";
}
else if(substr($content,0,1) == "#") {
return "<span class='label label-default'>$content</span>";
}
else if (substr($content,0,4) == "http" || substr($content,0,3) == "www") {
return "<span class='label'>$content</span>";
}
return $content;
}
}
And my controller in app/Controller/EntriesController:
App::uses('AppController', 'Controller');
class EntriesController extends AppController {
public $helpers = array('Form', 'Html', 'Js', 'Time');
#public $components = array('RequestHandler');
#public $viewClass = 'Json';
public function index() {
$helpers[] = 'spanWrapper';
$this->Entry->recursive = 1;
$this->set('entries', $this->paginate());
#$this->set('_serialize', array('entries'));
}
}
But a call from my View fails:
$this->Entries->spanWrapper($entry['Entry']['title']);
With the error:
Notice (8): Undefined property: View::$Entries [CORE/Cake/View/View.php, line 806]
Fatal error: Call to a member function spanWrapper() on a non-object in <path removed>/app/View/Entries/index.ctp on line 35
So the notice of undefined property is presumably causing the fatal error ... but why so, if it's implemented per the cookbook?
Darren
The correct syntax is $this->helpers[] = 'spanWrapper'; when loading a helper within a method, or add it to your public $helpers array instead.
If you want to use your helper in the entire controller, you should add it to the $helpers array in your EntriesController:
class EntriesController extends AppController {
public $helpers = array('Form', 'Html', 'Js', 'Time', 'Entries');
/* ... */
}
If you need the helper in your entire application, you can add it to the AppController the same way.
If on the other side you only need it in one single view, you may choose to only load it there dynamically. In your view, call HelperCollection->view() just before you want to use the helper for the first time:
$this->Helpers->load('Entries');
All three methods are documented very well in the CakePHP book.