TCPDF not working in cakephp 2.3.6 - cakephp

Hi i am trying to use the TCPDF manual given in cakephp.
http://bakery.cakephp.org/articles/kalileo/2010/06/08/creating-pdf-files-with-cakephp-and-tcpdf
But its not at all working in my system. I followed the exact steps there...
Error:-
Class 'XTCPDF' not found
But there is a class name XTCPDF in my Vendor folder....
Any help plz ??
Thanks

you try change:
App::import('Vendor','xtcpdf');
to
App::import('Vendor','tcpdf/xtcpdf');
or maybe following this tutorial:
http://www.pedroventura.com/cakephp/crear-archivos-pdf-con-cakephp/
summary:
file: app/vendors/tcpdf/xtcpdf.php
<?php
App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF creado using CakePHP y TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10);
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
function Footer()
{
$year = date('Y');
$footertext = sprintf($this->xfootertext, $year);
$this->SetY(-20);
$this->SetTextColor(0, 0, 0);
$this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
$this->Cell(0,8, $footertext,'T',1,'C');
}
}
?>
file: app/views/layouts/pdf.ctp
<?php
header("Content-type: application/pdf");
echo $content_for_layout;
?>
action in controller:
function descargar($id = null)
{
if (!$id)
{
$this->Session->setFlash('no has seleccionado ningun pdf.');
$this->redirect(array('action'=>'index'));
}
Configure::write('debug',0);
$resultado = $this->MiControlador->findById($id); // info from database
$this->set("datos_pdf",$resultado); // info to view (pdf)
$this->layout = 'pdf';
$this->render();
}
and
file: app/views/mi_aplicacion/descargar.ctp
<?php
App::import('Vendor','tcpdf/xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans';
$tcpdf->SetAuthor("");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',10));
$tcpdf->xheadercolor = array(255,255,255);
$tcpdf->xheadertext = 'Fecha: '. date('d-m-Y',time());
$tcpdf->xfootertext = 'www.example.cl';
$tcpdf->AddPage();
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',10);
$tcpdf->Cell(10,20,'Nombre:', 0, 0);
// more info
echo $tcpdf->Output('mi_archivo.pdf', 'D'); //D or I
?>

http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#loading-vendor-files Here you will find, how do you load vendor in CakePHP 2.3.6...

Related

Cant authentificate user with FOSUser bundle

I am creating an Angularjs app with Symfony 2.8 on the backend, using FOSUser bundle for the user management.
I have a controller to check the user login and create the user session, but when i try to create the user session symfony returns me this error message:
Controller "UserBundle\Controller\LoginController::indexAction()" requires that you provide a value for the "$session" argument (because there is no default value or because there is a non optional argument after this one).
There is my controller code:
<?php
namespace UserBundle\Controller;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use UserBundle\Entity\User;
class LoginController extends Controller
{
public function indexAction(Session $session)
{
$arrResult = array('STATUS' => 'ERROR', 'ERROR' => 'INIT', 'DATA' => array() );
// get post data
$postData = file_get_contents("php://input");
$postData = json_decode($postData, TRUE);
$email = $postData['email'];
$password = $postData['password'];
if( empty($email) || empty($password) )
{
$arrResult['ERROR'] = 'ALL_FIELDS_ARE_REQUIRED';
return new JsonResponse($arrResult);
}
$user_manager = $this->get('fos_user.user_manager');
$factory = $this->get('security.encoder_factory');
$user = $user_manager->findUserByEmail($email);
$encoder = $factory->getEncoder($user);
$salt = $user->getSalt();
if( $encoder->isPasswordValid($user->getPassword(), $password, $salt) )
{
// create user session
$this->createLoginSession($session, $user);
$arrResult['DATA'] = array('USERNAME' => $user->getUsername());
$arrResult['STATUS'] = 'OK';
}
else
{
$arrResult['ERROR'] = 'INVALID_CREDENTIALS';
}
return new JsonResponse($arrResult);
}
private function createLoginSession($session, $objUser)
{
$objToken = new UsernamePasswordToken($objUser, null, 'main', $objUser->getRoles() );
// save token
$objTokenStorage = $this->get("security.token_storage")->setToken($objToken);
$session->set( '_security_main', serialize($objToken) );
}
}
What i am doing wrong?
Thanks!

JRequest::getVar is keeping previous values even after refreshing

I am writing a mail function as a module in joomla 3. e mail works fine, but when i reload the page and insert a different email and send, but it seemed to return the previous email by JRequest::getVar function. Is there a way to solve this issue? thanks in advance..
this is the code i used:
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DS . 'helper.php');
//declaration
$input = JFactory::getApplication()->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
echo '<script>
var php_var = "chk is first:'.$email.'";
alert(php_var);
</script>';
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
echo '<script>
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);
</script>';
$input = JFactory::getApplication();//i have tried $app also
$input ->setUserState('mod_mycontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_myecontact', 'default_tmpl'));
}else{
require(JModuleHelper::getLayoutPath('mod_mycontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
#Mario this is the helper code:
class ModLittleContactHelper{
public function SendMail($email, $fname, $lname) {
$body = "<p style='font-family:arial;font-size:20px;'>Hi " . $fname . " " . $lname . ",</p>";
$body.="<p style='font-family:arial;font-size:20px;'>Welcome to Crowd Logistics! Please verify your email address below.</p><br/><br/>";
$body.= "<hr><br/>";
$body.= "<p style='align:center;background-color:#40B3DF;font-family:arial;color:#FFFFFF;font-size:20px;'><a href='http://suriyaarachchi.com/crowdlogistics/index.php?option=com_content&view=article&id=192' target='_blank'>Verify " . $email . "</a></p>";
$body.= "<br/><hr><br/>";
$body.="<p style='text-align:right;font-family:arial;font-size:20px;'>Or, paste this link into your browser:<br/>";
$body.= "http://crowdlogistics/index.php?option=com_content&view=article&id=192<br/><br/>";
$body.= "Thanks.<br/>";
$body.= "CrowdLogistics</p><br/>";
$mailer = & JFactory::getMailer();
$mailer->setSender('info#crowdlogistics.com');
$mailer->addRecipient($email);
$mailer->setSubject('Mail from CrowdLogistics - Confirm your email');
$mailer->setBody($body);
$mailer->IsHTML(true);
$send = & $mailer->Send();
return $send;
}
Since you're trying to run your code on Joomla 3, there are a few things that are wrong. Below os your code, corrected where I was able to correct it. Now you have to test it in your module environment with the class being instantiated (in other words, test the below code in your module).
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'helper.php');
//declaration
$doc = JFactory::getDocument();
$app = JFactory::getApplication();
$input = $app->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
$doc->addScriptDeclaration('
var php_var = "chk is first:'.$email.'";
alert(php_var);
');
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
$doc->addScriptDeclaration('
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);');
$app->setUserState('mod_littlecontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
break;
}else{
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
First, JRequest class is deprecated in J3. You should use JInput:
$input = JFactory::getApplication()->input;
$your_var = $input->get('your_var');
Then, regarding the email, you probably need to unset the session variables when the success is achieved (mail sent), or in other words, when you don't need them any longer.
$app = JFactory::getApplication();
// your_var is the variable you want to unset
$app->setUserState('mod_your_module.your_var', null);
Hope it helps
you can use this code
$email = $input->get('email', 0 , 'STRING','');
4th argument for the default value,

Pear::Image_Barcode output in CakePHP Controller

I want to output a barcode generated with PEAR::Image_Barcode in a CakePHP Controller:
public function gen_bc($bc_text = null)
{
$this->autoRender = false;
require_once("Image/Barcode.php");
$bc = new Image_Barcode;
$bc->draw($bc_text, "Code39", "jpg");
exit();
}
But i get no output # all.
You need to capture your output. Use ob_start(). Otherwise, you will only have the barcode image in your screen.
require_once('Image/Barcode.php');
public function gen_bc($bc_text){
ob_start();
$img = Image_Barcode::draw( $bc_text ,'code128', 'png', false);
$cif_data = ob_get_contents ();
ob_end_clean();
}
If you get an error, try to ommit the errors:
require_once('Image/Barcode.php');
error_reporting(0);
public function gen_bc($bc_text){
ob_start();
$img = Image_Barcode::draw( $bc_text ,'code128', 'png', false);
$cif_data = ob_get_contents ();
ob_end_clean();
}

CakePHP 2.2 - TCPDF - invalid property message

I have a problem with TCPDF:
viewPDF:
function viewPdf($id = null)
{
if (!$id)
{
$this->Session->setFlash('Sorry, there was no property ID submitted.');
$this->redirect(array('action'=>'index'), null, true);
}
Configure::write('debug',0); // Otherwise we cannot use this method while developing
$id = intval($id);
$property = $this->__view($id); // here the data is pulled from the database and set for the view
if (empty($property))
{
$this->Session->setFlash('Sorry, there is no property with the submitted ID.');
$this->redirect(array('action'=>'index'), null, true);
}
$this->layout = 'pdf'; //this will use the pdf.ctp layout
$this->render();
}
__view:
function __view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Calculation.', true));
$this->redirect(array('action'=>'index'));
}
$this->set('calculation', $this->Calculation->read(null, $id));
}
viewPDF.ctp:
<?php
App::import('Vendor','xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans'; // looks better, finer, and more condensed
than 'dejavusans'
$tcpdf->SetAuthor("KBS Homes & Properties a http://kbs-properties.com");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',20));
$tcpdf->xheadercolor = array(150,0,0);
$tcpdf->xheadertext = 'Test';
$tcpdf->xfootertext = 'Copyright © %d KBS Homes & Properties. All
rights reserved.';
// Now you position and print your page content
// example:
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',20);
$tcpdf->Cell(0,14, "Hello World", 0,1,'L');
// ...
// etc.
// see the TCPDF examples
$tcpdf->Output('filename.pdf', 'I');
?>
PDF layout for CakePHP 2.2 ($content_for_layout is depricated):
<?php
header("Content-type: application/pdf");
echo $this->fetch('content');
?>
xtcpdf.php in app/Vendor:
<?php
App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF created using CakePHP and TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
/**
* Overwrites the default header
* set the text in the view using
* $fpdf->xheadertext = 'YOUR ORGANIZATION';
* set the fill color in the view using
* $fpdf->xheadercolor = array(0,0,100); (r, g, b)
* set the font in the view using
* $fpdf->setHeaderFont(array('YourFont','',fontsize));
*/
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10); // shouldn't be needed due to page margin, but helas, otherwise it's at the page top
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
/**
* Overwrites the default footer
* set the text in the view using
* $fpdf->xfootertext = 'Copyright © %d YOUR ORGANIZATION. All rights reserved.';
*/
function Footer()
{
$year = date('Y');
$footertext = sprintf($this->xfootertext, $year);
$this->SetY(-20);
$this->SetTextColor(0, 0, 0);
$this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
$this->Cell(0,8, $footertext,'T',1,'C');
}
}
?>
And I always get "Sorry, there is no property with the submitted ID." and I don't see the problem.
you should have a look on this code :
function __view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Calculation.', true));
$this->redirect(array('action'=>'index'));
}
$data = $this->Calculation->read(null, $id));
return $data;
}

Drupal 7.14: Preprocess search block form gives me a blank form to render in $search_form

I've started working on a theme from scratch, I've tried to replace the title of the textfield but when imploding the search variable into search_form, the result is blank. Any error that I could be missing?
`function mytheme_preprocess_search_block_form(&$form) {
$form['search'] = array();
$hidden = array();
// Provide variables named after form keys so themers can print each element independently.
foreach (element_children($form['form']) as $key) {
echo $key;
$type = $form['form'][$key]['#type'];
echo '__'.$type.'<br />';
if ($type == 'hidden' || $type == 'token') {
$hidden[] = drupal_render($form['form'][$key]);
}
else {
if($key == 'search_block_form')
{
$form['form'][$key]['#title'] = t('');
//$form['search'][$key] = drupal_render($form['form'][$key]);
}
else
{
$form['search'][$key] = drupal_render($form['form'][$key]);
}
}
}
// Hidden form elements have no value to themers. No need for separation.
$form['search']['hidden'] = implode($hidden);
// Collect all form elements to make it easier to print the whole form.
$form['search_form'] = implode($form['search']);
var_dump($form);
exit;
}`
Refer to http://drupal.org/node/1092122:
<?php
/**
* Implements hook_theme().
*/
function MYMODULE_theme($existing, $type, $theme, $path) {
return array(
'article_node_form' => array(
'render element' => 'form',
'template' => 'article-node-form',
// this will set to module/theme path by default:
'path' => drupal_get_path('module', 'MYMODULE'),
),
);
}
?>
<?php
/**
* Preprocessor for theme('article_node_form').
*/
function template_preprocess_article_node_form(&$variables) {
// nodeformcols is an alternative for this solution.
if (!module_exists('nodeformcols')) {
$variables['sidebar'] = array(); // Put taxonomy fields in sidebar.
$variables['sidebar'][] = $variables['form']['field_tags'];
hide($variables['form']['field_tags']);
// Extract the form buttons, and put them in independent variable.
$variables['buttons'] = $variables['form']['actions'];
hide($variables['form']['actions']);
}
}
?>
article-node-form.tpl.php
<?php echo drupal_render_children($form)?>

Resources