cakephp find 'first' not pulling data - cakephp-2.0

I have a link that calls:
<span style="margin-left:24px;">Print</span>
It plugs in the correct id, and my route sends it to the correct view file. I have a debug command to show the entire array for the print page, but I'm getting an empty array. Here is my controller code:
<?php
class CouponsController extends AppController {
public $name='Coupons';
public $uses=array('User', 'Coupon', 'Restaurant');
public $layout='pagelayout';
public function print_coupon($name=null) {
$this->set('title', 'Print your coupon');
$f=$this->Coupon->find('first', array('conditions'=>array('Coupon.id'=>$this->params['id'])));
$this->set('name', $f);
}
}
?>
Here is my Coupon Model:
<?php
class Coupon extends AppModel {
public $name='Coupon';
var $belongsTo=array(
'Restaurant'=>array (
'className'=>'Restaurant',
'foreignKey'=>'restaurant_id'
)
);
}
?>
and here is my Restaurant Model:
<?php
class Restaurant extends AppModel {
public $name='Restaurant';
var $hasMany=array(
'Coupon'=>array(
'className'=>'Coupon',
'foreignKey'=>'restaurant_id'
)
);
var $belongsTo=array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user'
)
);
}
?>
I have tried variations using
<span style="margin-left:24px;">Print</span>
along with in my controller:
public function print_coupon($name=null) {
$this->set('title', 'Print your coupon');
$f=$this->Coupon->find('first', array('conditions'=>array('Coupon.id'=>$this->params['id'])));
$this->set('name', $f);
}
as well as a few others, and whenever I debug($name) I get an empty array. I have had no problems associating Coupon with my other models for other tasks yet, but i think something may be wrong with my Restaurant Model.
For reference, I have these are equal to each other:
Restaurants.coupon = Coupon.id
Coupon.restaurant_id=Restaurant.id

The first anchor code you posted has a curly brace that shouldn't be there. When you use this:
<span style="margin-left:24px;">Print</span>
It should yield some url that's like this:
/coupons/print_coupon/75
Then in your CouponsController that 75 turns into the $name in your print_coupon parameters (with default routing settings), I recommend changing that to $coupon_id, so your function should look like this:
public function print_coupon($coupon_id) {
$this->set('title', 'Print your coupon');
$f=$this->Coupon->find('first', array('conditions'=>array('Coupon.id'=>$coupon_id)));
$this->set('name', $f);
}
Now $name should be accessible in your view. With this code above, $name won't exist within the controller.
I don't think $this->params exists in Cake 2.*. debug($this->request->params); You can get the params from there in the controller, though.

Related

How to show data from (multidimensional?) arrays with Laravel 5.3 blade

Ok, so this is a question I hope can help other newbies as I'm running into errors pulling information from arrays in Blade and I'm unfamiliar with it's syntax to properly debug.
I understand how to send array data to the view normally, for instance:
public function index() {
$variable = DB::table('tablename')->where('ID', '535');
return view('viewname', compact('variable'));
}
This will send everything attached to the ID of 535 to the view. The title can then be printed out like so:
#foreach ($variable as $foo)
{{ $foo->title }}
#endforeach
Or if you want to print everything (I Think this is right?):
#foreach ($variable as $foo)
#foreach ($foo as $name)
{{ $name }}
#endforeach
#endforeach
That process I kind of understand.
But where I'm getting stuck is with models.
Let's say I set up some routes:
Route::get('User', 'UserEntryController#index');
route::get('User/{id}', 'UserEntryController#show');
And in the controller one that grabs the show route:
<?php
namespace App\Http\Controllers;
use App\UserEdit;
use Illuminate\Http\Request;
use App\Http\Requests;
class UserEntryController extends Controller
{
public function show(UserEdit $id) {
return $id;
}
}
This will return everything attached to the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserEdit extends Model {
protected $table = 'users';
protected $fillable = ['ID', various', 'pieces', 'of', 'table', 'data'];
protected $hidden = [];
protected $casts = [];
protected $dates = [];
}
However if I change a line on the controller:
<?php
namespace App\Http\Controllers;
use App\UserEdit;
use Illuminate\Http\Request;
use App\Http\Requests;
class UserEntryController extends Controller
{
public function show(UserEdit $id) {
return view('UserEdit', compact('id'));
//return $id;
}
}
The aforementioned Blade code will not run. In fact, I can't parse the array sent out to the the view at all. Of course a straight {{ id }} will give me the actual contents of the array.
{"ID":535,"various":"Del","pieces":"22","of":"32","table":"54","data":"John"}
So I guess my question is. If I'm getting data that's in the form of an array like this. How do iterate through it to apply formatting, put it in tables, or put it in a form, etc?
You're naming convention actually confuses you.
As long as you're returning and using a Object, rename that $id variable to something more obvious.
like:
class UserEntryController extends Controller
{
...
public function show(UserEdit $object) {
return view('UserEdit', compact('object'));
}
...
}
For the case when your framework is not set to bind directly to the object and your show method receives the $id, than you should return the object by querying the DB.
class UserEntryController extends Controller
{
...
public function show($id) {
$object = UserEdit::findOrFail($id);
return view('UserEdit', compact('object'));
}
...
}
... and nou in your view blade file you can use it like in your above examples.
#foreach ($object as $foo)
#foreach ($foo as $name)
{{ $name }}
#endforeach
#endforeach`

CakePHP form input filed empty after get submit

echo $this->Form->create('Driver', array('type' => 'get'));
echo $this->Form->input('name');
echo $this->Form->end('Search');
as result $this->request:
query => array(
'name' => 'some name'
)
Problem is input form is empty after search although $this->request->query['name'] = 'some name'
Everything works as expected when change form back to post
Edit. Included the model and the controller. For testing I use clean install.
Model (Driver.php):
App::uses('AppModel', 'Model');
class Driver extends AppModel {
public $displayField = 'name';
}
Controller (DriversController.php):
App::uses('AppController', 'Controller');
class DriversController extends AppController {
public function index() {
$drivers = $this->Driver->find('all');
$this->set(compact('drivers'));
}
}
In your controller code you do not show us where you are trying to access the submitted form values so I will try and give some general information to get you moving.
To access your form data, you need to cool use request. To see exactly what is going on, enter in your controller one of the below...
print_r($this->request->data);
or
print_r($this->request);
Either of those will show you any data registered with CakePHP.
If you want to save this save using your Models. use...
$this->Driver->save($this->request->data)
You might want to check it is a post first though.. lets complete the code...
public function submit() {
if ($this->request->is('post')) {
$this->Driver->create();
if ($this->Driver->save($this->request->data)) {
$this->Session->setFlash('Saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('FAILED');
}
}
}
The information above can be read in further detail here.
You can set form values by assigning to $this->data.
$this->data = $this->request->query;

CakePHP: Connection between model and controller failed

I've got a problem overhere with my newest CakePHP application.
I've made a model and controller for Categories.
Model: Categorie.php
class Categorie extends AppModel{
public $name = 'Categorie';
}
Controller: CategoriesController.php
class CategoriesController extends AppController {
public function index(){
$this->set('list', $this->Categorie->find('all'));
}
}
But when I visit the page I get the error:
Fatal error: Call to a member function find() on a non-object
When I add
$this->loadModel('Categorie');
to the index-function in my controller it will work.
So I guess the connection between the model and controller is not working but I'm not sure and I don't know how to fix this.
Please help me out.
thnx
CakePHP uses the controller names singular variant for matching the model, and the singular of categories is category, not categorie.
As #ndm said, you should use CakePHP conventions.
Your table should be called categories, then your model should look like this:
class Category extends AppModel{
}
And then you can include it with:
$this->loadModel('Category');
On CategoriesController you can use it like this:
class CategoriesController extends AppController {
public function index(){
$this->set('list', $this->Category->find('all'));
}
}
If you want to name your table otherwise, you can make use of $useTable variable in controller to specify the name of the table the model will work with.
You could also make use of the controller's $uses property:
public $uses = array('Categorie');

cakephp call a function of another model error

I have a site develop in cakephp 2.x
I want into my controller call a function of another controller like this:
class ProductsController extends AppController {
public $name = 'Products';
public $scaffold;
public $uses = array('Product','Unit');
public function testFunction(){
$this->loadModel('Unit');
$this->Unit->test();
}
}
The function test into UintController.php is this:
public function test(){
echo("test");
}
My model name are Product and Unit.
When I call the function test give me this error:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'prova' at line 1
In the function now is empty but give me this error.
I have tried with:
public $uses = array('Unit');
and to cancel the line with $uses.
How can I solve it?
To call a function from another controller you can use the requestAction:
Definition
"This function calls a controller’s action from any location and returns data from the action. The $url passed is a CakePHP-relative URL (/controllername/actionname/params). To pass extra data to the receiving controller action add to the $options array".
Usage
This is what your code would looks like:
class ProductsController extends AppController
{
public $name = 'Products';
public $scaffold;
public $uses = array('Product','Unit');
public function testFunction() {
// Calls the action from another controller
echo $this->requestAction('/unit/test');
}
}
And then in the UnitController:
class UnitController extends AppController
{
public function test()
{
return 'Hello, I came from another controller.';
}
}
Warning
As said in the CakePHP Cookbook:
"If used without caching requestAction can lead to poor performance. It is rarely appropriate to use in a controller or model".
Best solution for you
But, the best solution for you, would be to create a function inside a model and then call from your controller, like this:
class ProductsController extends AppController {
public $name = 'Products';
public $scaffold;
public $uses = array('Product','Unit');
public function testFunction() {
echo $this->Unit->test();
}
}
And in the Unit model:
class Unit extends AppModel
{
public function test(){
return 'Hello, I came from a model!';
}
}

Cakephp elements and for each loops

I'm breaking my head some time now on the following cakePHP code:
This is my controller:
<?php
class HeaderController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
}
public function usp() {
return $this->set('usp', $this->Header->query('SELECT * FROM USP WHERE Actief = 1'));
}
}
And this is my element:
<?
$UNSP = $this->requestAction('header/usp');
print_r($UNSP);
foreach($UNSP['header'] as $USPs):
echo $USPs['USP']['Naam'];
endforeach;
The query works and is executed when the page loads. I get an errormessage saying Invalid argument supplied for foreach() [APP/View/Elements/header.ctp, line 9]
Can somebody please help me with this?
You are assuming, somehow, that $UNSP in the view will be populated with the view variable you set in the usp() action. This is not how requestAction() works. requestAction() can either echo out the view that you call, or return the value of the function you're calling.
Instead, since it seems that usp() doesn't have a view but instead is just used to get data, you should return it like so
public function usp() {
return $this->Header->query('SELECT * FROM USP WHERE Actief = 1');
}
Then, in your view, tell requestAction() that you want the results of the function call:
$UNSP = $this->requestAction('header/usp', array('return'));
Now $UNSP should contain the results of the query.

Resources