how to reach database fields from default.ctp in Cakephp - cakephp

I'm unable to show a db field value in default.ctp , like unreaded messages or username ,
I keep getting Undefined variable: user, or message
how to reach them from default.ctp ?

Since your default layout is application wide, you will need to process data in the AppController.php in the beforeFilter method, so something like this
In AppController.php :
public function beforeFilter() {
//for example, you want to read messages
//import the Model
$this->loadModel('Message');
$all_messages = $this->Message->find('all'); //or whatever you need to do to get the data
$this->set('all_messages', $all_messages);
}
Then in your default.ctp,call the variable: $all_messages

Related

Self validation of links from HTML-Helper?

How can I prevent links automaticly from beeing displayed in the Template ctp files?
I will give you an example:
User(id = 1) is allowed to see teamcalendars/view/1
User(id = 2) is not allowed to see teamcalendars/view/1.
User1 is member of the team 1 and should see and follow the link. User2 is not member in any teams and neither should see the link to the calender nor follow it. But I would like to place the link in the teams/index file where both users can go to and see all teams, but with different options per team.
If User2 follows the link (or types it into the browser manually), the controller will return a redirect and a error message about missing privileges. User2 will anyhow never get there. But how do I prevent cake from displaying the link for User2 (its missleading)?
Is there a possibility to connect the link to the controller and action and the id of the object where it is leading to, so I don't neet to take care of building and passing variables for each view just to decide which links can be displayed?
Sorry for not providing any code, but I think anyone knows how to send an array from the Controller to the View and how to validate it with if(){echo $this->Html->link()}, which is what I am doing currently.
Thank you for any help or remarks in advance.
One option is to define your own HtmlHelper and override the link function, such that it checks the permissions on the link first and only outputs it if they are allowed access. Something like the following:
namespace App\View\Helper;
use \Cake\View\Helper\HtmlHelper;
// Or, if you're already using a third-party HTML helper, something like
// use BootstrapUI\View\Helper\HtmlHelper as HtmlHelper;
class MyHtmlHelper extends HtmlHelper
{
function link($title, $url = null, array $options = [])
{
if (checkMyPermissions($url)) {
return parent::link($title, $url, $options);
}
}
}
And then in your AppController:
use App\View\Helper\MyHtmlHelper;
public $helpers = [
'Html' => ['className' => 'MyHtmlHelper'],
// ... and all your other helpers
];

how to do not to go directly index.ctp when only cakephp/Controller/ instant of cakephp/Controller/index.ctp

Controller Name : SaleController.php
action name : index.ctp
When I write localhost/cakephp/Sale/index is written in address bar,
index page of SaleController is shown.
When I write localhost/cakephp/Sale/ is written in address bar,
index page of SaleController is shown.
Now,problem is I don't want to go index file when localhost/cakephp/Sale/ is written.
My cakephp version is 2.5.7.
If know ways,help me plz.
there is a lot of solutions :
Select view in the controller
in your SaleController.php
function index(){
$this->view="nameview.ctp";
}
Routes :
Router::connect(
'Sale/',
array('controller' => 'Sale' , 'action'=>'youraction' ),
array('option' => 'matchingRegex')
);
Select an other action in index
function index(){
$this->actionName();
}
First of all, your controller name should be SalesController (plural s).
Second, action is a method within controller not a file (here index mehod).
Third, index.ctp is a view file.
Fourth, you can change view in action method with render function (e.g. $this->render('other.ctp'); )
Fifth you can have custom URLs with routes.
And last but not least! you've not grabbed a good understanding of the framework, It's better to restudy the documentation.

Difference in accessing variables in views

I've two controllers one is "Upload" which deals with images uploads and other is "Page" whid deals with the creation of pages of CMS now if in my "Upload" controller I load both the models i.e 'image_m' which deals with image upload and "page_m" which deals with the pages creation I've highlighted the relevant code my problem is if I access the variables in the view
$this->data['images'] = $this->image_m->get(); sent by this I can access in foreach loop as "$images->image_title, $images->image_path" etc
But the variable sent by this line ***$this->data['get_with_images'] = $this->page_m->get_no_parents();*** as $get_with_images->page_name, $get_with_images->page_id etc produces given error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: upload/index.php
Line Number: 20
what is the difference between these two access levels one for $image & other for $get_with_images because I can only access its values as $get_with_images
class Upload extends Admin_Controller {
public function __construct() {
parent::__construct();
***$this->load->model('image_m');
$this->load->model('page_m');***
}
public function index($id = NULL) {
//var_dump($this->data['images'] = $this->image_m->get_with_images());
//$this->data['images'] = $this->image_m->get_with_images();
***$this->data['images'] = $this->image_m->get();***
$this->data['subview'] = 'admin/upload/index';
if ($id) {
$this->data['image'] = $this->image_m->get($id);
count($this->data['image']) || $this->data['errors'][] = 'Page Could not be found';
}
$id == NULL || $this->data['image'] = $this->image_m->get($id);
/*this calls the page_m model function to load all the pages from pages table*/
***$this->data['get_with_images'] = $this->page_m->get_no_parents();***
You are not posting all your code so its hard to tell but is it because you used $this-> in the controller, but you haven't done the same thing in the view?
In this case i would recommend not using $this-> because its not necessary. Also its much better to check for errors etc when you call the model so do something like
if ( ! $data['images'] = $this->image_m->get($id) ) {
// Failure -- show an appropriate view for not getting any images
// am showing $data in case you have other values that are getting passed
$this->load->view( 'sadview', $data ); }
else {
// Success -- show a view to display images
$this->load->view( 'awesomeview', $data ); }
so we are saying if nothing came back - the ! is a negative - then show the failure view. Else $data['images'] came back, and it will be passed to the view. note i have not had to use $this-> for anything and it won't be needed in the view.
Would also suggest using separate methods - have one method to show all images and a separate method like returnimage($id) to show an image based on a specific validated $id.
====== Edit
You can access as many models as you want and pass that data to the View. You have a different issue - the problem is that you are waiting until the View to find out - and then it makes it more difficult to figure out what is wrong.
Look at this page and make sure you understand the differences between query results
http://ellislab.com/codeigniter/user-guide/database/results.html
When you have problems like this the first thing to do is make a simple view, and echo out directly from the model method that is giving you problems. Its probably something very simple but you are having to look through so much code that its difficult to discover.
The next thing is that for every method you write, you need to ask yourself 'what if it doesn't return anything?' and then deal with those conditions as part of your code. Always validate any input coming in to your methods (even links) and always have fallbacks for any method connecting to a database.
On your view do a var_dump($get_with_images) The error being given is that you are trying to use/access $get_with_images as an object but it is not an object.
or better yet on your controller do a
echo '<pre>';
var_dump($this->page_m->get_no_parents());
exit();
maybe your model is not returning anything or is returning something but the data is not an object , maybe an array of object that you still need to loop through in some cases.

how to save data in one model from another controller in cakephp?

I have two controller name as ProductsController and Categories Controller and have there models.I have loaded Category model in ProductsController using
public function beforeFilter(){
$this->loadModel('Category');
}
In ProductsController When I use
$data = $this->Category->find('all', array('conditions'=>array('product_id'=>$id)));
it will return Value so that I can retrieve data from Category model .But I try to Save data in Category model from productsController using
$this->Category->save($this->request->data);
It doesnot work.When I debug to to see what it return,I get debug result as
\app\controller\ProductsController.php (line 74)
false
How to solve this problem any help?
Try to print data in $this->request->data before save and also print sql log
like
echo "<pre>";
print_r($this->request->data);
$this->Category->save($this->request->data);
$log=$this->Category->getDataSource()->getLog(false, false);
echo "<pre>";print_r($log);exit;
and make sure you have set debug to 2 in core.php

CakePHP Component not working

Hey guys, I'm working on a cakephp app that manages a list of alpha users. It's a simple form that accepts a name and email and then generates an alpha code after submission, that alpha code is then stored in the record with the name and email under the column "code." I'm using a component calleed PasswordHelper which is located here
Here' my code
class AlphaUsersController extends AppController {
var $name = 'AlphaUsers';
var $components = array('PasswordHelper');
function add() {
if(!empty($this->data)) {
if($this->AlphaUser->save($this->data)){
$this->AlphaUser->set('code', generatePassword(10));
$this->AlphaUser->save();
$this->Session->setFlash('User has been added.');
$this->redirect(array('action' => 'index'));
}
}
}
}
The form data saves just fine when I don't include the alpha code lines, but when I try to generate the password, I get this error.
Fatal error: Call to undefined function generatepassword() in /Users/Warren/Sites/caroverload/app/controllers/alpha_users_controller.php on line 22
What's going on here? I have the PasswordHelper file saved in the appropriate components directory and it's added in the components array for this controller.
I think the way you are calling the PasswordHelper methods should look more like this: $this->PasswordHelper->generatePassword(10).
As you have it now, it is looking for that as a global function, which doesn't exist and throws the error.

Resources