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
Related
I am being shown the following error on top of my page when using beforeSave method in my Upload model.
Strict (2048): Declaration of Upload::beforeSave() should be
compatible with Model::beforeSave($options = Array)
[APP/Model/Upload.php, line 5]
Could someone point out what I'm doing wrong?
Here is my model:
<?php
App::uses('AppModel', 'Model');
class Upload extends AppModel {
protected function _processFile() {
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$name = md5($file['name']);
$path = WWW_ROOT . 'files' . DS . $name;
if (is_uploaded_file($file['tmp_name'])
&& move_uploaded_file($file['tmp_name'], $path) ) {
$this->data['Upload']['name'] = $file['name'];
$this->data['Upload']['size'] = $file['size'];
$this->data['Upload']['mime'] = $file['type'];
$this->data['Upload']['path'] = '/files/' . $name;
unset($this->data['Upload']['file']);
return true;
}
}
return false;
}
public function beforeSave() {
if (!parent::beforeSave($options)) {
return false;
}
return $this->_processFile();
}
}
?>
Just change this line
public function beforeSave() {
to this, so you have correct method declaration
public function beforeSave($options = array()) {
The beforeSave() function executes immediately after model data has been successfully validated, but just before the data is saved. This function should also return true if you want the save operation to continue.
This callback is especially handy for any data-massaging logic that needs to happen before your data is stored. If your storage engine needs dates in a specific format, access it at $this->data and modify it.
Below is an example of how beforeSave can be used for date conversion. The code in the example is used for an application with a begindate formatted like YYYY-MM-DD in the database and is displayed like DD-MM-YYYY in the application. Of course this can be changed very easily. Use the code below in the appropriate model.
public function beforeSave($options = array()) {
if (!empty($this->data['Event']['begindate']) &&
!empty($this->data['Event']['enddate'])
) {
$this->data['Event']['begindate'] = $this->dateFormatBeforeSave(
$this->data['Event']['begindate']
);
$this->data['Event']['enddate'] = $this->dateFormatBeforeSave(
$this->data['Event']['enddate']
);
}
return true;
}
public function dateFormatBeforeSave($dateString) {
return date('Y-m-d', strtotime($dateString));
}
Make sure that beforeSave() returns true, or your save is going to fail.
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?
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.
This is my test:
public function testIncludeNumComment() {
$post = array(...stuff.....);
$result = $this->Comments->includeNumComments($post);
echo "end"; //this is not printed
$expected =1;
$this->assertEquals($result, $expected);
}
Then, my controller function is this one:
public function includeNumComments($post){
echo "printed";
$comments = $this->Comment->getNumComments($post['Post']['id']);
echo "not printed";
return $comments;
}
As you can see, this call on the controller to the model function doesn't work
$this->Comment->getNumComments($idPost);
And what is more, when i introduce an echo "hi"; at the very start of the getNumComments function inside the Comment model, it is not printed either.
It's like it didn't find the function or something like that. (but it doesn't show any error by screen during the test)
It stops there and it doesn't execute more code.
I am completely sure that function works well, it just returns the number of comments from a post. The question is: why it isn't working on the test case?
Thanks.
UPDATE:
The test setUp looks like this:
public function setUp() {
parent::setUp();
$this->Comments = new TestCommentsController();
$this->Comments->constructClasses();
}
$result = $this->Comments->includeNumComments($post);
this doesnt make much sense if your model is "Comment"
so change it to:
$result = $this->Comment->includeNumComments($post);
Check that you include the TestCommentsController like following:
App::uses('TestCommentsController', 'Controller');
Then write beforeFilter function in AppController like following:
class AppController extends Controller {
......
...
public function beforeFilter() {
// you stuff
}
}
Then add this to you controller which contains test function:
public function beforeFilter(){
parent::beforeFilter();
$this->Comments = new TestCommentsController();
$this->Comments->constructClasses();
}
.....
NOW keep going with...
public function testIncludeNumComment() {
$post = array(...stuff.....);
$result = $this->Comments->includeNumComments($post);
echo "end"; //this is not printed
$expected =1;
$this->assertEquals($result, $expected);
}