CakePHP Custom Helper not working - cakephp

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();
}

Related

How to use library function in view in cakephp?

I created my own library file in :
app/lib/mylib.php
in mylib.php I have a function :
<?php
class Mylib {
public function get_discount($item){
$this->loadModel('ServiceCharge');
$this->loadModel('ZeroServiceCharge');
$service_crages=$this->ServiceCharge->find('all');
$zero_service_charge=$this->ZeroServiceCharge->find('all');
$zero_service_charge=$zero_service_charge[0]['ZeroServiceCharge']['items'];
if( $item>=$zero_service_charge){
return 100;
}
foreach ($service_crages as $service_crage) {
pr($service_crage);
exit;
//if($service_crage)
}
}
}
?>
Then I add the following line app/controller/AppController.php:
App::uses('Mylib', 'Lib');
and finally I call this function in nocontact.ctp :
echo get_discount( $total_pieces);
But it shows the following error:
Error: Call to undefined function get_discount()
Whats wrong am I doing?
App::uses('Lib', 'Mylib');
class yourController extends AppController{
public function viewPage(){
$this->set('variableToView', $this->get_discount($param));
}
}
View:
echo $variableToView

Symfony 2 how to call the renderView method in FormHandler?

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?

Create and save in component , from different controller to diffrent model.non-object error

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();

Custom Helper in CakePHP Error

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.

cakephp2.x component not working

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 { ... }

Resources