Render to different view Cakephp 3 - view

I'm beginning to work on CakePHP and I'm stucked on a problem.
I have an Articles controller inside a blog project and I want to display the X last articles on my home page which is the home.ctp in the Pages template.
Here is my Articles function in Articles controller :
public function recentArticles(){
$recentArticles = $this->Articles->find('all', [
'limit' => 5,
'order' => 'Articles.created DESC'
]);
$this->set('recentArticles', $recentArticles);
$this->render('/Pages/home');
}
And here is my section in the template where I try to display the articles :
<?php foreach ($recentArticles as $article): ?>
<section class="col-4-ligne">
<?=$this->Html->image('slide3.jpg', array('alt' => 'nom du slide', 'class' => 'img-responsive'))?>
<section class="btn btn-lg btn-danger principale"><?= $article->title ?></section>
</section>
<?php endforeach; ?>
I tried to use $this->render in the controller, I also tried to put my function into the Pages controller like this :
public function recentArticles(){
$this->loadModel('Articles');
$recentArticles = $this->Articles->find('all', [
'limit' => 5,
'order' => 'Articles.created DESC'
]);
$this->set('recentArticles', $recentArticles);
$this->render('/Pages/home');
}
But in each case I get the same error in my template which is "Undefined variable: recentArticles".
Any idea ?
EDIT : Ok so I didn't success to call the recentArticles function so I put the code into the default function display like this and it works.
I don't know if it's good way to do it.
public function display()
{
$path = func_get_args();
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
$page = $subpage = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
$this->set(compact('page', 'subpage'));
//Latest articles
$this->loadModel('Articles');
$recentArticles = $this->Articles->find('all', [
'limit' => 5,
'order' => 'Articles.created DESC'
]);
$this->set('recentArticles', $recentArticles);
try {
$this->render(implode('/', $path));
} catch (MissingTemplateException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
}

Related

Yii2 how to send controller action response without redirect?

I have a Single page application in Yii2
the main page contains
1. a column with a list of objects + create button
2. a column for dynamic content of create/update forms
My problem is when loading (through ajax) a create form, and then I am sending data through AjaxSubmitButton which woks fine (db updated) but instead of changing the dynamic content area with the new object data it redirects to a view partial form.
How can I make the new response go into the same div that it is being sent from?
this is the form that is loaded now in #singleObjContainer
<div class="course-form">
<?php
$form = yii\bootstrap\ActiveForm::begin();
?>
<span>
<h4 class='listTitle'>Add Course</h4>
</span>
<span class="form-group pull-right">
<?php
AjaxSubmitButton::begin([
'label' => 'Save',
'ajaxOptions' => [
'type'=>'POST',
'url'=> Url::toRoute(['course/create-form']),
'success' => new \yii\web\JsExpression('function(html)
{
$("#singleObjContainer").empty().append(html);
}'),
],
'options' => ['class' => 'btn btn-success', 'type' => 'submit'],
]);
AjaxSubmitButton::end();
?>
</span>
<hr class='myHr'>
<div>
<?php
echo $form->field($model, 'name')->textInput(['maxlength' => true]);
echo $form->field($model, 'description')->textarea(['rows' => '4']);
echo $form->field($model, 'img')->label(Html::img(Yii::getAlias('#uploadsUrl/').'courses/'.$model->img,['width' => '30%']),['encodeLabel' => false])->fileInput();
?>
</div>
<?php ActiveForm::end(); ?>
and this is the controller action:
public function actionCreateForm()
{
$model = new Course();
if ( $model->load(Yii::$app->request->post()))
{
// get the instance of the image
$image = UploadedFile::getInstance( $model, 'img');
// save image name to the model
$model->img = $image->baseName.".".$image->extension;
// go through validation rule and save
if( $model->save() )
{
// validation ok, save image in the file system
$image->saveAs( Yii::getAlias('#uploads/').'courses/'.$model->img);
// load the details view into the singleObj container
$courseStudents = $this->getCourseStudents($model['id']);
return $this->renderPartial('_viewForm', ['model' => $model, 'courseStudents' => $courseStudents]);
}
}
else
{
return $this->renderPartial('_createForm', ['model' => $model,]);
}
}
If you need that your result is send directly to the ajax request .. just return .. eventually using a json_encode for the array.
return json_encode( $model);
this way you obtain a json answer with struct equivalent to your $model
In your controller add a proper action
public function actionRefreshForm()
{
//your appllication code
$my_new_html_code ='<div>test new html code </div>;
return $my_new_html_code;
}
In your ajaxOptions call the related action
'ajaxOptions' => [
'type'=>'POST',
'url'=> Url::toRoute(['course/refresh-form']),
'success' => new \yii\web\JsExpression('function(html)
{
$("#singleObjContainer").empty().append(html);
}'),
],
You can use yii\widgets\Pjax. It will be easy for you I guess. You can learn more about it in this article. http://blog.neattutorials.com/yii2-pjax-tutorial.

Yii's default ajax is not working

In my Yii application, Yii's default Ajax is not working. Also default Ajax validation is not working. Has this been an installation problem or any other problem. How to enable Yii's default Ajax.
In my controller,
public function actionCreate() {
$model = new Company;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if (isset($_POST['Company'])) {
$company = Company::model()->findAll();
if (count($company) === 0) {
$model->attributes = $_POST['Company'];
$uploadedFile = CUploadedFile::getInstance($model, 'logo');
if (isset($uploadedFile)) {
$fileName = date('Ymdhis') . '_' . $uploadedFile->name; // $timestamp + file name
$model->logo = $fileName;
}
if ($model->validate()) {
if ($model->save()) {
if (isset($uploadedFile)) {
$uploadedFile->saveAs(Yii::app()->basePath . '/../banner/' . $fileName);
}
$this->redirect(array('create'));
}
}
} else {
Yii::app()->user->setFlash('error', 'Company details is already exists.');
}
}
$this->render('create', array(
'model' => $model,
));
}
In view page,
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'company-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<div class="form-group">
<?php echo $form->label($model, 'company_name', array('class' => 'req')); ?>
<?php echo $form->textField($model, 'company_name', array('class' => 'form-control')); ?>
<?php echo $form->error($model, 'company_name', array('class' => 'school_val_error')); ?>
</div>
Please help me.
Thanks...
Yii has no default AJAX. This is a technology based on JavaScript language. By default Yii includes a jQuery library which provided some methods for easy manipulations with AJAX. If you want use it on your page, you should add this string:
Yii::app()->clientScript->registerCoreScript('jquery');
You can add this string to your main layout, for example into top of /views/layouts/main.php`

Displaying form validation errors in a template (Symfony)

let's say I have a blog with a module "post".
now I display a post like this: post/index?id=1
in the index-action i generate a new CommentForm and pass it as $this->form to the template and it is being displayed at the bottom of a post (it's just a textfield, nothing special). form action is set to "post/addcomment". How can I display the validation errors in this form? using setTemplate('index') doesn't work because I would have to pass the id=1 to it...
thanks
UPDATE:
here's a sample code:
public function executeIndex(sfWebRequest $request)
{
$post = Doctrine::getTable('Posts')->find($request->getParameter('id'));
$this->post = $post->getContent();
$comments = $post->getComment();
if ($comments->count() > 0)
$this->comments = $comments;
$this->form = new CommentForm();
$this->form->setDefault('pid', $post->getPrimaryKey());
}
public function executeAddComment(sfWebRequest $request) {
$this->form = new CommentForm();
if ($request->isMethod('post') && $request->hasParameter('comment')) {
$this->form->bind($request->getParameter('comment'));
if ($this->form->isValid()) {
$comment = new Comment();
$comment->setPostId($this->form->getValue('pid'));
$comment->setComment($this->form->getValue('comment'));
$comment->save();
$this->redirect('show/index?id='.$comment->getPostId());
}
}
}
and my Comment Form:
class CommentForm extends BaseForm {
public function configure() {
$this->setWidgets(array(
'comment' => new sfWidgetFormTextarea(),
'pid' => new sfWidgetFormInputHidden()
));
$this->widgetSchema->setNameFormat('comment[%s]');
$this->setValidators(array(
'comment' => new sfValidatorString(
array(
'required' => true,
'min_length' => 5
),
array(
'required' => 'The comment field is required.',
'min_length' => 'The message "%value%" is too short. It must be of %min_length% characters at least.'
)),
'pid' => new sfValidatorNumber(
array(
'required' => true,
'min' => 1,
'max' => 4294967295
),
array(
'required' => 'Some fields are missing.'
))
));
}
}
and finally, indexSuccess:
<?php echo $post; ?>
//show comments (skipped)
<h3>Add a comment</h3>
<form action="<?php echo url_for('show/addComment') ?>" method="POST">
<table>
<?php echo $form ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
that's it.
If you're using sf 1.4 just put executeAddComments and executeIndex together in one function (executeIndex for example) and you'll be fine. setTemplate won't work here.
Are you using the handleError method in the action ? The id=1 part of your url should not change if inside the handleError method, you do a return sfView::SUCCESS;
UPDATE:
It actually changes, what you need to do is submit the id along with the comment [Which I'm sure you're already doing because a comment that doesn't refer to a post doesn't make much sense], then in your handleError method, instantiate the post object there.
Try to change your form action to
<?php echo url_for('show/addComment?id=' . $post->getId()) ?>
Doing this, your post id parameter should be available even on your post request, and it should work with setTemplate('index') or forward at the end of executeAddComment

Validation in my CakePHP seems disabled

I'm following the blog tutorial on CakePHP website, but validation doesn't work and I don't understand why, because I'm using the blog tutorial code.
I'll report directly from my files anyway...
MODEL
class Post extends AppModel
{
var $name = 'Post';
var $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
CONTROLLER
class PostsController extends AppController {
var $name = 'Posts';
function index() {
$this->set('posts', $this->Post->find('all'));
}
function view($id) {
$this->Post->id = $id;
$this->set('post', $this->Post->read());
}
function add() {
if (!empty($this->data)) {
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
}
VIEW (add view)
<h1>Add Post</h1>
<?php
echo $form->create('Post');
echo $form->input('title');
echo $form->input('body', array('rows' => '3'));
echo $form->end('Save Post');
?>
When I reach the /posts/add page and then click to Save without any input text it doesn't reload with error; it inserts the empty data into db and then redirects me with the message "Your post has been saved".
Why doesn't validate itself? I've read into docs that it's not necessary to call validate(); save() is enough.
Any ideas about this?
I found the error: I was naming the model files capitalizing them. So, I had a Post.php instead of a post.php.
CakePHP didn't find my models and so it was using its "generated" models.

Why aren't validation errors being displayed in CakePHP?

I'm trying to perform validation in the login page for the name,email and password fields. If the input fails validation,the error message should be displayed.
But here,when I fill in the details and submit, it is redirected to the next page. Only the value is not saved in the database.
Why is the message not displayed?
This is my model:
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Mimimum 8 characters long'
),
'email_id' => 'email'
);
function loginUser($data) {
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
$login = $this->find('all');
foreach ($login as $form):
if ($this->data['User']['email_id'] == $form['User']['email_id'] && $this->data['User']['password'] == $form['User']['password']) {
$this->data['User']['id'] = $this->find('all',
array(
'fields' => array('User.id'),
'conditions' => array(
'User.email_id' => $this->data['User']['email_id'],
'User.password'=>$this->data['User']['password']
)
)
);
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
function registerUser($data) {
if (!empty($data)) {
$this->data['User']['name'] = $data['User']['name'];
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
if($this->save($this->data)) {
$this->data['User']['id']= $this->find('all', array(
'fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
}
This is my controller:
class UsersController extends AppController {
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function login() {
$userId = $this->User->loginUser($this->data);
if($userId>0) {
$this->Session->setFlash('Login Successful.');
$this->redirect('/forms/homepage/'.$userId);
break;
} else {
$this->flash('Login Unsuccessful.','/forms');
}
}
function register() {
$userId=$this->User->registerUser($this->data);
$this->Session->setFlash('You have been registered.');
$this->redirect('/forms/homepage/'.$userId);
}
}
EDIT
Why is the message,example,"Minimum 8 characters long", is not being displayed when give less than 8 characters in the password field?
<!--My view file File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="appTitle">
<h2> formBuildr </h2>
</div>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->error('User.name','Name not found');
echo $form->input('User.email_id');
echo $form->error('User.email_id','Email does not match');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Your validation seems correct
How about trying the following:
Make sure set your $form->create to the appropriate function
Make sure there is no $this->Model->read() before issuing Model->save();
Edit
Did you have the following?:
function register()
{
//do not put any $this->User->read or find() here or before saving pls.
if ($this->User->save($this->data))
{
//...
}
}
Edit2
IF you're doing a read() or find() before saving the Model then that will reset the fields. You should be passing the variable as type=hidden in the form. I hope i am making sense.
Edit3
I think you need to move your registerUser() into your controller because having that function in the model doesn't provide you a false return. it's always going to be true even if it has validation errors.
Comment out the redirect line and set the debug to 2 in config/core.php. Then look at the sql that is being generated to see if your insert is working. If the errors are not being displayed, maybe in the view, you are using $form->text or $form->select instead of the $form->input functions. Only the $form->input functions will automatically display the error messages.

Resources