My index post controller list all posts in the following way
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>"{items}\n{pager}",
)); ?>
My view _view has the ajax-link
<div id="comments"></div>
<?php echo CHtml::ajaxLink('List Comments', array('listComments'),
array('update' => '#comments'))?>
listComments is a function in my PostController
public function actionListComments()
{
$this->renderPartial('_comments',array(
'post'=>$model,
'comments'=>$model->comments,
));
}
When I click to the ajax link , nothing happens,
it points to localhost/blog/#
Can you help me please ?
The problem is actionListComments() method returns non-200 HTTP code because of undefined $model variable in it. Try something like this:
_view:
<div id="comments"></div>
<?php echo CHtml::ajaxLink('List Comments', array('listComments', 'id' => $data->id),
array('update' => '#comments'))?>
PostController:
public function actionListComments($id)
{
$model = Posts::model()->findByPk($id);
if($model !== null)
$this->renderPartial('_comments',array(
'post'=>$model,
'comments'=>$model->comments,
));
else
Yii::log('Unknown post with $id ' . $id, 'error');
}
First in actionListComments() you have a variable $model which you haven't instantiated.
Assuming you are getting the $model->id from the link it should change to:
<?php echo CHtml::ajaxLink('List Comments', array('listComments','id'=>$data->id),
array('update' => '#comments'))?>
Next, your actionListComments() should access the id, use this to load a model and its comments, and send this to the required view
public function actionListComments($id){
$model=$this->loadModel($id);
$this->renderPartial('_comments',array('model'=>$model));
}
There is no need to send $model->comments as we are already sending $model therefore we can access $model->comments.
many things could go wrong about that. As ajax calls cant be debugged with normal compnonents like
CVarDumper::Dump();
die();
Above code will not show you anything in the browser area. The best way to debug ajax calls is using inspectElement. Click on Network. Now when you click on ajaxLink it will show you whether the ajax request was sent successfully. It will be red if the request was unsuccessful. When you click on the request made. It will show you 3 tabs on right named Header, Preview, Response. As you want to render the page so the content-Type should be text/html.
As far as your code is concerned clearly you are using $model without instantiating it so it is returning error.
Read the error returned in your case.
Related
this is the Session class in Session.php file
<?php
namespace app\core;
class Session
{
public function __construct()
{
session_start();
}
public function setFlash($key='', $message='')
{
$_SESSION['flash'][$key] = $message;
}
public function getFlash($key='')
{
return $_SESSION['flash'][$key] ?? false;
}
public function __destruct()
{
unset($_SESSION['flash']);
}
}
then i called session::setFlash() before redirecting the user to the home page after registering
and call session::getFlash() in the view or the layout does not matter but i displayed nothing
here is the code
public function register(Request $request)
{
$registerModel = new RegisterModel;
if($request->isPost())
{
$registerModel->loadData($request->getBody());
if($registerModel->validate() && $registerModel->save())
{
Application::$app->session->setFlash('success', 'Thanks for registering');
$this->redirect('.');
}
return $this->render('register', [
'model' => $registerModel
]);
}
$this->setLayout('auth');
return $this->render('register', [
'model' => $registerModel
]);
}
this the view
<div class="container">
<?php if(Application::$app->session->getFlash('success')):?>
<div class="alert alert-success">
<?php echo Application::$app->session->getFlash('success'); ?>
</div>
<?php endif; ?>
{{content}}
</div>
i don`t know why it does not work
Two probable suspects:
You are unsetting the 'flash' index when destructing the session. This means that when ONE request ends (the first one), the data is cleared. I'd recommend you rather remove a specific key from this array when calling getFlash(), so that every message is only gotten once.
When the second request is already handled but the session was not written to the storage yet (which is usually handled asynchronously by PHP), you may want to add a call to session_write_close(). This immediately ends the session and writes data to the session storage directly, making it available for the second request (the one that comes after the redirect). You have to call this before making the redirect.
Side note: Your "custom MVC framework" code looks like it could live inside Laravel. If it does, the redirect() method may already call the session_write_close() so my second point would be moot.
I am trying to make a simple ajax request in Ajax in Yii
I have my view file views/items/index.php and a controller file controllers/ItemsController.php
I have inserted a link in my view file
echo CHtml::ajaxLink(
'Test request', // the link body (it will NOT be HTML-encoded.)
array('ajax/reqTest01'), // the URL for the AJAX request. If empty, it is assumed to be the current URL.
array(
'update'=>'#req_res'
)
);
?>
<div id="req_res">...</div>
I have this code in my controller file
public function actionReqTest01() {
echo date('H:i:s');
Yii::app()->end();
}
But Nothing is happening it is giving error 404 (as checked in chrome network tab)
Create Another controller named AjaxController.php
write this code in that.
class AjaxController extends Controller
{
public function actionReqTest01() {
echo date('H:i:s');
Yii::app()->end();
}
}
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.
I am using this extension of the CI_Session Class. To create flash data and style them using TW Bootstrap. However when I go to pass the "Success" message to the view it's just not loading in at all.
I have had a good luck but no joy with it.
My Controller looks like this..
// Set form Validation
$this->form_validation->set_rules('title', 'Title', 'required|trim|is_unique[films.title]');
if($this->form_validation->run() == FALSE)
{
$data['page_title'] = 'Add New DVD';
$this->load->view('_partials/_header', $data);
$this->load->view('_partials/_menu');
$data['genres'] = $this->genre_model->get_genres();
$data['classification'] = $this->classification_model->get_classifications();
$this->load->view('create', $data);
$this->load->view('_partials/_footer');
}
else
{
// Insert into DB
$film_data = array
(
'title' => $this->input->post('title'),
'genre_id' => $this->input->post('genre'),
'classification_id' => $this->input->post('classification')
);
$this->film_model->create($film_data);
$this->session->set_success_flashdata('feedback', 'Success message for client to see');
redirect('dvd');
and my View is....
<?php $this->session->flashdata('feedback'); ?>
So when I insert a new item to the DB, The Model runs, The redirect runs but the "set_success_flashdata" doesnt.
The MY_session library is set to load automatically as per CI's default config.
How do I get this damn Flash Message to show ::( ?
It is not set_success_flashdata it is just set_flashdata.
Change in Controller :
$this->session->set_flashdata('feedback', 'Success message for client to see');
View is just as it is :
echo $this->session->flashdata('feedback');
Hope this helps you. Thanks!!
Although I fail to see the point of this particular extension, the answer is simple enough.
You are not echoing the data from the Session Library.
The correct way to echo flashdata is like so:
<?php echo $this->session->flashdata('feedback'); ?>
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...