View file is missing when outputting CSV - cakephp

I'm using CakePHP 2.x, and running it locally on IIS. I'm following the tutorial on Exporting data to CSV the CakePHP way, and I'm getting an error.
The URL I'm entering is like: http://myproject.localhost/territory/spreadsheet.csv
I have Router::parseExtensions('csv'); as the first thing in app\Config\routes.php
Here's my controller:
`class TerritoryController extends AppController
{
public $useTable = 'ezrep_territory';
public $paginate = array('limit' => 50);
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->deny('index');
}
public function Index()
{
// ... snip ...
}
public function Spreadsheet()
{
$data = $this->Territory->find(
'all',
array(
'conditions' => array('Territory.ez' => $this->ez),
'fields' => array('territory','terrcode','terrdesc'),
'contain' => false
));
$headers = array(
'Territory'=>array(
'territory' => 'Territory ID',
'terrcode' => 'Terr Code',
'terrdesc' => 'Terr Desc'
)
);
array_unshift($data,$headers);
$this->set(compact('data'));
}
}
`
In app\View\Layouts\csv, I have a file default.ctp:
<?php
echo $content_for_layout;
?>
And in app\View\Territory, I have a file spreadsheet.ctp:
// Loop through the data array
foreach ($data as $row)
{
// Loop through every value in a row
foreach ($row['Territory'] as &$value)
{
// Apply opening and closing text delimiters to every value
$value = "\"".$value."\"";
}
// Echo all values in a row comma separated
echo implode(",",$row['Territory'])."\n";
}
When I go to http://myproject.localhost/territory/spreadsheet.csv, I get a page that appears to be rendered through the app\View\Layouts\default.ctp with an error:
View file "C:\zproj\ezrep40\app\View\Territory\csv\spreadsheet.ctp" is missing.
and
Error: An Internal Error Has Occurred.
What am I doing wrong?

This is not right
And in app\View\Territory, I have a file spreadsheet.ctp:
you'll need to place also the view, and not just the layout, in a sub directory named after the extension:
app\View\Territory\csv\spreadsheet.ctp

Related

Yii2 using array to build activeform - cannot get & echo second array element

I have created and registered a Yii2 component function 'formSchema' which
contains the array as such:
class FormSchema extends Component{
public function formSchema()
{
$fields = array(
['field' => 'username', 'controltype' => 'textinput'],
['field' => 'email', 'controltype' => 'textArea'],
);
return $fields;
}
}
?>
I call the array in the active form, however I cannot get the
['controltype'] using the same successful method as I do to retrieve ['field'] as
below. I would like to get that array element however seem unable to get any but the first level element:
<div class="usermanager-form">
<?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
<?php
$fields = $items = Yii::$app->formschema->formSchema();
foreach($fields as $field)
{
$field = $field['field'];
echo $form->field($model, $field);
}
?>
You may use array values in this way:
$fields = Yii::$app->formschema->formSchema();
foreach ($fields as $field) {
echo $form->field($model, $field['field'])->{$field['controltype']}();
}

CakePHP Model validation not working properly

I am new to CakePHP and have created a normal form to submit first name.
My table name is "registers. I have created a controller named RegistersController (RegistersController.php) and a model named Register (Register.php) . Each time i submit after entering first name, it still displays error (First name is must) which it should only if i submit it without entering anything. Next i added validation for having minimum 6 characters. That validation is also not working. I mean, cakephp is not validating that rule. Could anyone please tell me where i have done anything wrong?
Model:-
class Register extends AppModel {
//put your code here
//public $useTable = "registers";
public $validate = array(
'first'=>array(
'minLength' => array(
'rule' => array('minlength','6'),
'field' => 'first',
'message' => 'Minimum 6 characters required'
),
'required' => array(
'rule'=>array('notEmpty'),
'required' => true,
'message' => array('First name is must')
)
)
);
}
Controller:-
class RegistersController extends AppController {
public $uses = array("Register");
//put your code here
public function index() {
if($this->request->is('post')){
//echo "Data";
if($this->Register->validates()){
//$this->Register->create();
//echo "Data validated";
print_r($this->Register->validationErrors);
}else{
//echo "Data not validated";
print_r($this->Register->validationErrors);
}
}
}
My view is as follows:-
<?php
echo $this->Form->create('Register');
echo $this->Form->input('first');
echo $this->Form->end("Submit");
?>
You are missing this line
$this->Register->set($this->request->data);
Put it before the validation call, i.e.
$this->Register->validates()

How to populate select element in zend 1.12 from db

i'm creating a application in which i need to populate data in select element from a db table.
i need to populate user roles from db
my form code is
$this->pass2->addValidator('Identical', false, array('token' => 'pass1'));
$this->addElement('select', 'userrole', array(
'class' => 'form-control',
'required' => true,
'multiOptions' =>
));
what should i do with multi options ?,
is there any way to load data from db in element using controller ,please helpme
thanks
What I have done in the past is to pass the db-adapter (or a model that knows how to do the required db query) to the form as a constructor parameter.
Something like this:
class Application_Form_MyForm extends Zend_Form
{
protected $db;
public function __construct($db)
{
$this->db = $db;
// Don't forget to call the parent __construct. Ultimately
// it is the parent __construct() that calls your init()
// method that adds your elements
parent::__construct();
}
public function init()
{
// Create your form elements
// $this->addElement('text', 'my_text_field'); // etc
// Now your select field...
$this->addElement('select', 'my_select', array(
'multiOptions' => $this->buildMultiOptions(),
'validators' => array(
// blah, blah
),
);
}
protected function buildMultiOptions()
{
$select = $this->db->select()
->from('my_table', array(
'my_value_column',
'my_display_column'
))
->order(array(
'my_display_column ASC',
));
$results = $this->db->query($select)->fetchAll();
$return = array();
foreach ($results as $row) {
$return[$row['my_value_column']] = $row['my_display_column'];
}
return $return;
}
}
Then in the controller action, when you instantiate your form, you grab the db-adapter and pass it in as a constructor parameter:
$db = $this->getInvokeArg('bootstrap')->getResource('db');
$form = new Application_Form_MyForm($db);
// Then process your form as usual
on case with is necessary populate options outside form class.
$form->getElement( 'ele_name' )
->setConfig(new Zend_Config( array(
'multiOptions' => array('option1','option2') )
)));

CakePHP 3: Export to excel files

I'm new to CakePHP, I'm using version 3.0, and have asked before how to export to Excel using PHPExcel. I have downloaded and installed it in the vendor folder and created the different files as follows:
controller
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Tests Controller
*
* #property \App\Model\Table\TestsTable $Tests
*/
class TestsController extends AppController
{
var $helpers = array('Html', 'Form','Csv','PHPExcel');
public function exportoexcel()
{
$this->set('data',$this->Tests->find('all'));
$this->response->download("export.xls");
}
}
src/template/.ctp
<?php
$this->PhpExcel->createWorksheet()
->setDefaultFont('Calibri', 12);
// define table cells
$table = array(
array('label' => __('User'), 'filter' => true),
array('label' => __('Type'), 'filter' => true),
array('label' => __('Date')),
array('label' => __('Description'), 'width' => 50, 'wrap' => true),
array('label' => __('Modified'))
);
// add heading with different font and bold text
$this->PhpExcel->addTableHeader($table, array('name' => 'Cambria', 'bold' => true));
// add data
foreach ($data as $d) {
$this->PhpExcel->addTableRow(array(
));
}
// close table and output
$this->PhpExcel->addTableFooter()
->output();
?>
In the src/view/helper folder I have created the phpexcel.php and phpexcelhelper file .
Then when I run the application I always get this error:
require(C:\wamp\www\qualite2\qualite\src\View\Helper\PHPExcel\Autoloader.php): failed to open stream: No such file or directory [APP/View\Helper\PHPExcel.php, line 32]
Code Context
if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', dirname(__FILE__) );
require(PHPEXCEL_ROOT . '\PHPExcel\Autoloader.php');

Download function not working CakePHP

I read the documentation regarding file downloads, however I can't seem to get this to work.
I have read through questions here as well, and have had no luck.
My function looks as follows:
public function generate($id) {
$this->layout = 'ajax';
$this->Magazine->recursive = 2;
$DistributionLists = $this->Magazine->DistributionList->find('all',
array(
'conditions' => array(
'Magazine.id' => $id
),
'order' => array(
'DistributionList.priority ASC'
)
)
);
$this->set('magazine',$DistributionLists[0]['Magazine']['magazine_name']);
$this->set(compact('DistributionLists'));
}
public function download() {
$this->viewClass = 'Media';
$params = array(
'id' => "Magazine Distribution List.doc",
'name' => "Magazine Distribution List",
'download' => true,
'extension' => 'doc',
'path' => APP . "tmp" . DS
);
$this->set($params);
unlink(APP."tmp".DS);
$this->redirect(array('action'=>'index'));
}
public function afterFilter() {
parent::afterFilter();
if($this->action == 'generate') {
$this->redirect(array('action'=>'download'));
}
}
The reason I have an afterFilter function is because the word document that needs to be downloaded is created in the view file.
Does anyone know why this doesn't work?
You have to remove the call to the redirect method in your download method because it prevents your view from getting "rendered" due to the redirect.

Resources