How to pass $$variables to view from controller in CakePHP? - php

in AppController:
function beforeFilter() {
$company = 'name of Company';
$this->set(compact('company'));
}
in Controller class:
function companyinfo() {
$logo = '<div><?php $this->Html->image('logo'); ?></div>';
$welcome = 'welcome to $$company!';
$this->set(compact('logo','welcome'));
}
function beforeFilter() {
parent::beforeFilter();
}
in View class:
<html>
<body>
<?php echo $logo; ?>
<?php echo $welcome; ?>
</body>
</html>
it doesn't answer variable in view after passing the variable from AppController via controller..

1) When you use $this->set(compact('company'));, it is NOT setting a variable for use in any controller - it's passing $company to the view.
2) You're trying to write PHP code in a string, using a Helper (which are only available in Views)
$logo = '<div><?php $this->Html->image('logo'); ?></div>';
3) It's unusual to want to pass data from AppController to Controller to View.
What you probably want to do is something like this:
//App Controller
function beforeFilter() {
$company = 'name of Company';
$this->set(compact('company'));
}
//Controller
function companyinfo() {
$logo = 'logo';
$this->set(compact('logo'));
}
//Layout file (or view file, but I assume it's layout since you're getting data in the AppController)
<?php
echo '<div>' . $this->Html->image($logo) . '</div>';
echo "Welcome to " . $company;
I mean this in the most constructive way possible (we've all been there). It seems like you're struggling with some general PHP concepts. Before you get too heavy into CakePHP, I recommend trying out a few lengthy tutorials in generic PHP - then when you feel completely comfortable with it, dive into CakePHP.

To get company into the view you can set it in your appcontroller if you want it avaiable in ALL views throughout your site or inside a specific controller if you only want it available in the view of the function you set it inside of. Either way you'll need to make correct use of the set function. For example:
$this->set('company', 'Name of Company');
OR
$company = 'Name of Company';
$this->set('company', $company);
Afterwards you'll be able to access the $company variable in the view.
echo $company; outputs Name of Company
As for your question for Dave:
<?php $welcome = 'Welcome to $$company'; ?> <html><body><?php echo $welcome; ?></body></html>
would be written as:
<html><body><?php echo "Welcome to ". $company; ?></body></html>
However, you should really look into using layouts with cakephp so you don't need to the <html>, <head>, <body>, etc. tags in every view file

Related

How can I put all includes on one page with classes?

For a school project I need to put all returning code into an include. I want it all on one page, but I can't get it to work. Creating an include is no problem, but I want them all in one PHP page. I have the following code, but it is wrong:
//footer
<?php
class footer
{
echo 'Account';
echo 'Subscription';
echo 'About us';
echo 'Terms of Use';
echo '<small>© 2017, (myname) & (name partner)</small>';
}
?>
How do I have to modify the code, so that it is correct?
Assign the html code to variables.
<?php $footer = "Account
Subscription
About us
Terms of Use
<small>© 2017, (myname) & (name partner)</small>"
?>
After that you only need to include the one PHP file and <?php echo $footer ?> for all parts of your page
You got it wrong. You will only declare methods(functions), properties(variables) and constants directly in a class body.
If you want to run echoes, you should declare it inside a method.
An example for your case:
class Footer
{
public static function printLinks()
{
echo 'Account';
echo 'Subscription';
echo 'About us';
echo 'Terms of Use';
echo '<small>© 2017, (myname) & (name partner)</small>';
}
}
Then call it in every place that you want it as:
Footer::printLinks(); //This will call all those echoes at once

Passing value through url

I am trying to send a url from view page to controller but it does not seem to work the way i am thinking.
View Page
Product
User
I want to get "tbl_product"
Controller admin
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->uri->segment(4);
}
}
?>
but if the segment(4) is changed to segment(3), it shows up with displaying "product" in the screen
your controller function should have arguments for your url segments
for example:
public function test($product = 'product', $tbl = 'tbl_product') {
echo $tbl // contains the string tbl_product
}
Since you said your routes look like this:
$route['default_controller'] = "admin";
$route['404_override'] = ''
and your URL is like this:
<?= base_url() ?>admin/test/product/tbl_product
Then if your base_url() is localhost/my_app, your URL will be read as this:
http://localhost/my_app/admin/test/product/tbl_product
http://localhost/my_app/CONTROLLER/METHOD/PARAMETER/PARAMETER
So in your controller, you can do this:
class Admin extends CI_Controller {
public function test($product = NULL, $tbl_product = NULL) {
echo $product;
echo $tbl_product;
}
}
It's strange to use codeigniter for this purpose, because codeigniter uses as default the url format bellow.
"[base_url]/[controller]/[method]"
I think it will be better and more easy to just pass the values you want as get parameters and make some httaccess rules to make your url more readable for the user and robots. That said you can do that:
Product
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->input->get('product');
//should output 'tbl_product'
}
}
?>
If you prefer to use uri instead u should route your uri's so it will be like.
In your routes file you probably I'll need something like this.
$route['product/(:any)'] = "Admin/test";
This way you will probably access the uri segments correctly.
Thank you so much for going through.
$this->uri->segment(4); // is now working :S
its not working properly after all I made changes to routes.php and came back to default again. I seriously have no idea what the reason behind not displaying the result before.

Page Title Based on Class/Function Variable PHP

New to classes, and I'm having an issue dynamically changing a page's title. I think I may know what the issue is, but I don't really know what to do in order to fix the problem. I have two pages, admin.php (where the class is housed) and display-admin.php (displays what the user sees). Within admin.php this is what I have:
class Admin {
public $title;
public function login() {
require("login-form.php");
return $this->title = "Login";
}
...
}
$o = new Admin();
This is what I have within display-admin.php:
<?php
include_once("admin.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
if(isset($o->title)) {
echo "<title>My Site | " . $o->title . "</title>";
} else {
echo "<title>My Site</title>";
}
?>
</head>
<body>
<?php
...
switch($action) {
case "login":
$o->login();
break;
default:
$o->displayPages();
}
...
?>
</body>
</html>
The title always stays as My Site. It never adds the title needed. Now, when I tested echoing $o->title at the end (before the <\body> tag), it displayed the string I passed. Is this because I am trying to echo the variable before calling the function? If so, how do I fix in order to display the title, and have my content displayed within the body?
Thanks in advance for the any/all help/suggestions.
In your case it isnt work because $o->title doesnt exist.
It is created in your "login()" method, and this is after your
if(isset($o->title)) {
So you can do this:
class Admin {
public $title;
public function __construct() {
$this->title = "Admin";
}
}
You can do it per example in the constructor of your Admin Class.
The constructur is a magic method. It will be automatically called directly if you created your class.
Hope this will help you.
If you create an object from class Admin the title will be change into 'Admin'
In your Admin Page you can do this:
$o = new Admin();
echo "<title>".$o->title."</title>";

Zend Framework 2 Flash Messenger returning no messages

I'm having a rather odd problem with flash messenger in ZF2. I'm using it in quite a simple scenario, save a 'registration complete' message after registering and redirect to the login page and display the message however the messages are never returned by the flash messenger.
In controller register action:
$this->flashMessenger()->addMessage('Registration complete');
return $this->redirect()->toRoute('default', array('controller' => 'user', 'action' => 'login'));
In controller login action:
$flashMessenger = $this->flashMessenger();
$mes = $flashMessenger->hasMessages();
$cur = $flashMessenger->hasCurrentMessages();
Both $mes and $cur are false (I tried both just to be sure). Can anyone shed any light on this?
I'm using ZF 2.2.2 and PHP 5.3.14. Session save handler is using the dbtable adapter and I have tried disabling this as well as setting the flashmessenger session manager to the use the same dbtable save handler with no result.
To use the FlashMessenger controller plugin, you need to add the following in your controller:
<?php
class IndexController extends AbstractActionController {
public function indexAction() {
$this->flashMessenger()->addMessage('Your message');
return $this->redirect()->toRoute('admin/default', array('controller'=>'index', 'action'=>'thankyou'));
}
public function thankyouAction() {
return new ViewModel();
}
}
Add the following to the thankyou.phtml view template:
<?php
if ($this->flashMessenger()->hasMessages()) {
echo '<div class="alert alert-info">';
$messages = $this->flashMessenger()->getMessages();
foreach($messages as $message) {
echo $message;
}
echo '</div>';
}
?>
It seems that your code is as it should be, there must be something tricky in the workflow.
In this case, you can debug the old way : try var_dump($_SESSION) to see if it is populated by your flashMessenger.
Use
echo $this->flashMessenger()->renderCurrent(...
instead of
echo $this->flashMessenger()->render(...
I also faced same problem for (login flashmessage after registration) I solved it in the following way
Apply a check on your layout page like
<?php if($this->zfcUserIdentity()) { ?>
<div id="flashMessageDiv" class="hide">
<?php echo isset($flashMessages) && isset($flashMessages['0']) ? $flashMessages['0'] : ''; ?>
</div>
<?php } ?>
That means layout flashMessageDiv is accessible only to the logined user . now on your login view file (login.phtml)
apply the following code
<?php $pathArray = $_SERVER['HTTP_REFERER'];
$pathArray = explode("/",$pathArray);
?>
<?php if ($pathArray[4] === 'register') { ?>
<div id="flashMessageDiv" class="hide">
<?php echo "User details saved successfully"; ?>
</div>
<?php } ?>
In the above code i used HTTP_REFERER which will simply give us the referer url details check if referer url is register then show falshmessage.
Hope it will help you.
The FlashMessenger is now an official view helper in ZF2 and can be easily integrated in every view / layout:
FlashMessenger Helper — Zend Framework 2 2.3.1 documentation - Zend Framework
It works with TwitterBootstrap3 too and there is an alternative configuration for your module.config.php.

cakephp displaying posted form data

I'm new to cakephp and trying to simply display form data once it is posted. I would like to type something on "add.ctp" which then redirects to "index.ctp" where the information I just typed should be displayed.
The reason why I'm doing this is because I like to echo my variables and forms at various places throughout my program for debugging purposes. I tend to work a lot with data that needs to be converted or manipulated so I like to check and make sure each part is doing its job correctly. I'm new to cakephp so I'm just trying to figure out how I can do this.
Here is the code for add.ctp where the information is entered.
View\Mysorts\add.ctp
<h1>Add Numbers</h1>
<?php
echo $this->Form->create('Mysort');
echo $this->Form->input('original');
echo $this->Form->end('Add Numbers');
?>
Here is my function in the controller
Controller\MysortsController.php
<?php
class MysortsController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
$this ->set('mysorts', $this->Mysort->find('all'));
}
public function add() {
if($this->request->is('post')) {
Configure::read();
pr($this->data); //attempting to print posted information
$this->redirect(array('action' => 'index'));
}
}
function isempty(){
$mysorts = $this->Mysort->find('all');
$this->set('mysorts', $mysorts);
}
}
?>
And finally, here is my index file where I would like to display the posted information.
View\Mysorts\index.ctp
<h1>Sorted Entries</h1>
<?php
echo $this->Html->link("Add List", array('controller'=>'mysorts', 'action' => 'add'));
if (!empty($mysorts)) {
?>
<table>
<tr>
<th>ID</th>
<th>Original</th>
<th>Sorted</th>
</tr>
<?php foreach ($mysorts as $mysort): ?>
<tr>
<td><?php echo $mysort['Mysort']['id']; ?></td>
<td>
<?php echo $mysort['Mysort']['original']; ?>
</td>
<td> <?php echo $mysort['Mysort']['sorted']; ?>
</td>
</tr>
<?php endforeach;
} else {
echo '<p>No results found!</p>';
}
?>
</table>
If the code you have posted is the exact you are using that could not work at all.
You do not save the data you receive while being in the "add" method. This is done by $this->ModelName->save($data) where ModelName is the Model to use (in your case it should be MySort and $data is the posted data.
You are using Cakephp2.x? I assume so cause you are using $this->request->is('post') which was not there in 1.3, i think. The problem about that is, that the posted data is not stored in $this->data anymore. It is in $this->request->data.
Do not use pr(). It is too "dangerous" to forget something like that in the code. Use debug() instead. The output will be disabled as soon as you see the DEBUG constant in Config/core.php in your application root to 0.
Calling the redirect() method in a controller generates a real 301 redirect. Which means the old output is dumped and lost. That and point 1 makes clear why you can not see anything. Nothing is saved and before you see the output of pr() your browser gets redirected. If you want to debug something use an exit; afterwards to make sure you wont miss the output. Sometimes you do not need it, but if you can not find your output, use it ;)
Hope this helps you.
Greetings
func0der
Maybe what you need is something like this.
For your add.ctp you define the action you want your post.
<h1>Add Numbers</h1>
<?php
echo $this->Form->create(array('action' => 'view'));
echo $this->Form->input('original');
echo $this->Form->end('Add Numbers');
?>
For your Controller You'll need to set the variable you want in your view
public function add() {
}
public function index(){
if($this->request->is('post')) {
$this->set('mysorts', $this->request->data);
}
}
And I'm not sure if what I see in your index.ctp makes sense.
I don't understand what your point is in trying to print something and then redirecting immediately? You won't see it when it redirects.
Anyhow, since your Form probably does not consist of a representation of an actual model, you might want to inspect your $this->params['form'] variable as opposed to the normal $this->data that you would use in a FormHelper.
Also, do you realize you are missing a closing } in your Controller\MysortsController.php? It closes the add() function but not the class...

Categories