CakePHP 2.x Translate Behavior Not Saving to i18n Table - php

I've followed the instructions in the manual for setting up Translate Behavior with CakePHP 2.1, as well as this question here on Stack. I am not getting any errors, but my translated posts are not saving to my i18n table.
Here is my PostModel.php:
class Post extends AppModel {
public $title = 'Post';
public $name = 'Post';
public $body = 'Post';
public $actAs = array(
'Translate' => array(
'title' => 'titleTranslation',
'body' => 'bodyTranslation'
)
);
public $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
And here are my add and edit functions in PostsController.php:
public function add() {
if ($this->request->is('post')) {
$this->Post->locale = 'fre';
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.', true));
$this->redirect(array('action' => 'admin'));
} else {
$this->Session->setFlash(__('Unable to add your post.', true));
}
}
}
public function edit($id = null) {
$this->Post->id = $id;
if ($this->request->is('get'))
{
$this->Post->locale = 'fre';
$this->request->data = $this->Post->read();
}
else
{
if ($this->Post->save($this->request->data))
{
$this->Post->locale = 'fre';
$this->Session->setFlash(__('Your post has been updated.', true));
$this->redirect(array('action' => 'admin'));
}
else
{
$this->Session->setFlash(__('Unable to update your post.', true));
}
}
}
I initialized the i18n table using Console. Should I drop the table and try reinitializing? Not sure why there would be a problem there.

More reusable solution is to add to your AppModel:
class AppModel extends Model {
public $actsAs = array('Containable');
/**
* Converts structure of translated content by TranslateBehavior to be compatible
* when saving model
*
* #link http://rafal-filipek.blogspot.com/2009/01/translatebehavior-i-formularze-w.html
*/
public function afterFind($results, $primary = false) {
if (isset($this->Behaviors->Translate)) {
foreach ($this->Behaviors->Translate->settings[$this->alias] as $value) {
foreach ($results as $index => $row) {
if (array_key_exists($value, $row)) {
foreach($row[$value] as $locale) {
if (isset($results[$index][$this->alias][$locale['field']])) {
if (!is_array($results[$index][$this->alias][$locale['field']])) {
$results[$index][$this->alias][$locale['field']] = array();
}
$results[$index][$this->alias][$locale['field']][$locale['locale']] = $locale['content'];
}
}
}
}
}
}
return $results;
}
}
This code automatically converts what returns TranslateBehavior to be able to create multi-language form like:
echo $this->Form->input('Category.name.eng');
echo $this->Form->input('Category.name.deu');
echo $this->Form->input('Category.name.pol');
Tested on CakePHP 2.3. And I discovered that now Model->saveAssociated() is required instead of Model->save().

Try to add this in your form on add.ctp:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('Post.title.fre');
echo $this->Form->input('Post.body.fre');
//Something more...
echo $this->Form->end(__('Submit'));
?>
in your edit.ctp:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('id');
echo $this->Form->input('Post.title.fre', array('value'=>$this->request->data['titleTranslation'][0]['content'));
echo $this->Form->input('Post.body.fre', array('value'=>$this->request->data['bodyTranslation'][0]['content'));
//Something more...
echo $this->Form->end(__('Submit'));
?>
assuming index of data['titleTranslation'][0] is in French, to easily see an array in the view I recommend to use DebugKit https://github.com/cakephp/debug_kit
I hope this will help

Use saveMany instedof save. it's working fine for me.

For those who have the same problem: the correct variable is $actsAs, not $actAs.

Related

ArgumentCountError Too few arguments to function App\Controllers\Blog::view()

Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).

Cake php ajax layout cache

After any ajax request all subsequent non ajax request is returning with ajax layout instead of default layout.
Obs:
Ocurrs only on production enviroment.
Configure::write('Cache.disable', true); // Don't have any effect!
Cake Version 2.4.4
After 20 ~ 30 seconds the layout (default) is rendered.
config/core.php is identical.
I don't no why , and i loose 8 hours on that, any tip?
The controller (But any ajax on any controller cause the problem:
<?php
App::uses('AppController', 'Controller');
class NewslettersController extends AppController
{
public $paginate = array(
'limit' => 20,
'paramType' => 'querystring',
'order' => array(
'Newsletter.created' => 'DESC'
)
);
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow(array('add','push'));
}
public function admin_index()
{
$this->set('dataGrid', $this->paginate('Newsletter'));
}
public function admin_view($id = null)
{
$this->Newsletter->id = $id;
$result = $this->Newsletter->read();
if (!$result) {
$this->setFlashMessage('Cadastro não encontrado', 'error', array('action' => 'index'));
return false;
}
$this->set('dataGrid', $result);
}
public function admin_delete($id = null)
{
$this->Newsletter->id = $id;
if (!$this->Newsletter->exists()) {
$this->Session->setFlash('O item solicitado não foi encontrado!', 'alert_error');
$this->setFlashMessage('O item solicitado não foi encontrado!', 'error', array('action' => 'index'));
}
try {
if ($this->Newsletter->delete($id, false)) {
$this->setFlashMessage('Item excluído com sucesso!', 'success', array('action' => 'index'));
}
} catch (Exception $e) {
$this->setFlashMessage('Não foi possivel excluir este item pois existem itens atrelados a ele', 'error', array('action' => 'index'));
}
}
public function admin_search()
{
$this->autoRender = false;
$conditions = null;
if (isset($this->request->query['search']) && !empty($this->request->query['search'])) {
$conditions[] = array(
'OR' => array(
'Newsletter.name LIKE' => '%' . $this->request->query['search'] . '%',
'Newsletter.email LIKE' => '%' . $this->request->query['search'] . '%',
)
);
$this->paginate['conditions'] = $conditions;
$this->set('dataGrid', $this->paginate());
$this->render('admin_index');
}
}
//######################
//# FRONTEND #
//######################
public function push()
{
if($this->Newsletter->save($this->request->data))
{
$response = array("result"=>true,"id"=>$this->Newsletter->id);
}
else
{
$response = array("result"=>false,"errors"=>$this->Newsletter->validationErrors);
}
return new CakeResponse(array("body" => json_encode($response),"type" => "json"));
}
}
?>
You have to differentiate the layout for ajax in the method, please the following changes I made in the above code:
...
class NewslettersController extends AppController
{
public layout = 'default';
...
public function push() // if this is ajax function
{
$this->layout = 'ajax'; //put this for ajax functions only
....
}
...
}
Hope it helps!

CakePHP Form Validation Not Working

I've been learning how to use CakePHP using a video tutorial series, and I'm having issues with validation on forms. I've tried several different things that I've found on the CakePHP book and it doesn't seem to be working either. It's pretty simple validation, just making sure that the title isn't empty or duplicate, and that the post isn't empty, yet the form is still submitting regardless of whether it's blank or duplicate.
Here is my model:
class Post extends AppModel {
var $name = 'Post';
var $validate = array(
'title'=>array(
'title_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'This post is missing a title!'
),
'title_must_be_unique'=>array(
'rule'=>'isUnique',
'message'=>'A post with this title already exists!'
)
),
'body'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'This post is missing its body!'
)
)
);
}
Here is the controller:
class PostsController extends AppController {
var $name = 'Posts';
function index() {
$this->set('posts', $this->Post->find('all'));
}
function view($id = NULL) {
$this->set('post', $this->Post->read(NULL, $id));
}
function add() {
if (!empty($this->request->data)) {
if($this->Post->save($this->request->data)) {
$this->Session->setFlash('The post was successfully added!');
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('The post was not saved... Please try again!');
}
}
}
function edit($id = NULL) {
if(empty($this->data)) {
$this->data = $this->Post->read(NULL, $id);
} else {
if($this->Post->save($this->data)) {
$this->Session->setFlash('The post has been updated');
$this->redirect(array('action'=>'view', $id));
}
}
}
function delete($id = NULL) {
$this->Post->delete($id);
$this->Session->setFlash('The post has been deleted!');
$this->redirect(array('action'=>'index'));
}
}
And here is the view:
<h2>Add a Post</h2>
<?php
echo $this->Form->create('Post', array('action'=>'add'));
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Create Post');
?>
<p><?php echo $this->Html->link('Cancel', array('action'=>'index')); ?></p>
Thanks in advance!
The problem is that the rules you're trying to use aren't defined in the CakePHP framework. If you want to require something and make sure the field isn't empty you should try this:
'title' => array(
'required' => array(
'rule' => array('minLength', 1),
'allowEmpty' => false,
'message' => 'Please enter a title.'
)
),
The 'required' key tells Cake that the field is required while 'allowEmpty' => false tells Cake that the field needs to contain something and can't just be an empty string.

CakePHP 2.0, Submit form redirect not rendering properly

Hi I've created a file upload form, it all works perfectly apart from when I press submit it does not re-direct me to the Uploads/add.ctp, but it does save the file to the directory and on to the database.In fact if I point the re-direct to uploads/browse it still does not take me to uploads/browse.
This is my controller
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else{
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
and this is my form
<div class="maincontent">
<?php echo $this->Form->create('Upload', array('type' => 'file', 'class'=>'uploadfrm'));?>
<fieldset class='registerf'>
<legend class='registerf2'>Upload a Video</legend>
<?php
echo 'Upload your video content here, there is no size limit however it is <b>.mp4</b> file format only.';
echo '<br/>';
echo '<br/>';
echo $this->Form->input('name', array('between'=>'<br />', 'class'=>'input'));
echo $this->Form->input('eventname', array('between'=>'<br />'));
echo $this->Form->input('description', array('between'=>'<br />', 'rows'=> '7', 'cols'=> '60'));
echo $this->Form->hidden('userid', array('id' => 'user_id','value' => $auth['id']));
echo $this->Form->hidden('username', array('id' => 'username', 'value' => $auth['username']));
echo $this->Form->input('file', array('type' => 'file'));
echo "<br/>"
?>
<?php echo $this->Form->end(__('Submit', true));?>
</fieldset>
<?php
class UploadsController extends AppController {
public $name = 'Uploads';
public $helpers = array('Js');
// Users memeber area, is User logged in…
public $components = array(
'Session',
'RequestHandler',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'uploads', 'action'=>'browse'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
'authError'=>"Members Area Only, Please Login…",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
// regular user can access the file uploads area
if (isset($user['role']) && $user['role'] === 'regular') {
return true;
}
// Default deny
return false;
}
function index() {
$this->set('users', $this->Upload->find('all'));
}
// Handling File Upload Function and updating uploads database
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4'))
{
$this->redirect(array('controller' => 'Uploads', 'action' => 'add'));
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
} }else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
function browse () {
// Find all in uploads database and paginates
$this->paginate = array(
'limit' => 5 ,
'order' => array(
'name' => 'asc'
)
);
$data = $this->paginate('Upload');
$this->set(compact('data'));
}
function recentuploads () {
$uploads = $this->Upload->find('all',
array('limit' =>7,
'order' =>
array('Upload.date_uploaded' => 'desc')));
if(isset($this->params['requested'])) {
return $uploads;
}
$this->set('uploads', $uploads);
}
function watch ($id = null){
$this->set('isAjax', $this->RequestHandler->isAjax());
// Read Uploads Table to watch video
$this->Upload->id = $id;
$this->set('uploads', $this->Upload->read());
// Load Posts Model for comments related to video
$this->loadModel('Post');
$this->paginate = array(
'conditions' => array(
'uploadid' => $id),
'limit' => 4
);
$data = $this->paginate('Post');
$this->set(compact('data'));
// Load Likes Model and retrive number of likes and dislikes
$this->loadModel('Like');
$related_likes = $this->Like->find('count', array(
'conditions' => array('uploadid' => $id)
));
$this->set('likes', $related_likes);
}
}
?>
Any suggestions?
This add function is in your UploadsController, correct? And you want it to redirect to uploads/browse?
In your UploadsController, what is $name set to?
<?php
class UploadsController extends AppController {
public $name = ?; // What is this variable set to?
}
By Cake's Inflector, when you specify controllers in a redirect, it should be lowercase:
$this->redirect(array('controller' => 'uploads', 'action' => 'browse'));
Or if the action you direct from and the action you want to direct to are in the same controller, you do not even need to specify the controller. For example if you submit the form from UploadsController add() and you want to redirect to browse():
$this->redirect(array('action' => 'browse'));
Try that and see if it helps.
Also note that you are calling $this->Upload->save($this->data) twice in your add function.
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
Specifically, here:
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
...
When you call it in the if condition, it still saves the data to the database. It is fine to remove the second one.
If I add the following line in the function add
$this->render();
everything works perfectly, I'm struggling for the life of me to work out why I have to render the view if surely all other views are rendered by default.
But anyway got it working!
Hope this helps others :)

Kohana 3: Example of model with validation

I find examples and tutorials about models and about validation. And I places that say the validation (or most of it at least) should be in the model, which I agree with. But I can't any examples or tutorials that show how that should be done.
Could anyone help me with a simple example on how that could be done? Where would you have the rules in the model? Where would the validation happen? How would the controller know if the validation passed or fail? How would the controller get error messages and things like that?
Hope someone can help, cause feel a bit lost here :p
I too had difficulty finding examples for Kohana3, bestattendance's example is for Kohana2.
Here's an example I threw together in my own testing:
application / classes / model / news.php
<?php defined('SYSPATH') OR die('No Direct Script Access');
Class Model_News extends Model
{
/*
CREATE TABLE `news_example` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`title` VARCHAR(30) NOT NULL,
`post` TEXT NOT NULL);
*/
public function get_latest_news() {
$sql = 'SELECT * FROM `news_example` ORDER BY `id` DESC LIMIT 0, 10';
return $this->_db->query(Database::SELECT, $sql, FALSE)
->as_array();
}
public function validate_news($arr) {
return Validate::factory($arr)
->filter(TRUE, 'trim')
->rule('title', 'not_empty')
->rule('post', 'not_empty');
}
public function add_news($d) {
// Create a new user record in the database
$insert_id = DB::insert('news_example', array('title','post'))
->values(array($d['title'],$d['post']))
->execute();
return $insert_id;
}
}
application / messages / errors.php
<?php
return array(
'title' => array(
'not_empty' => 'Title can\'t be blank.',
),
'post' => array(
'not_empty' => 'Post can\'t be blank.',
),
);
application / classes / controller / news.php
<?php defined('SYSPATH') OR die('No Direct Script Access');
Class Controller_News extends Controller
{
public function action_index() {
//setup the model and view
$news = Model::factory('news');
$view = View::factory('news')
->bind('validator', $validator)
->bind('errors', $errors)
->bind('recent_posts', $recent_posts);
if (Request::$method == "POST") {
//added the arr::extract() method here to pull the keys that we want
//to stop the user from adding their own post data
$validator = $news->validate_news(arr::extract($_POST,array('title','post')));
if ($validator->check()) {
//validation passed, add to the db
$news->add_news($validator);
//clearing so it won't populate the form
$validator = null;
} else {
//validation failed, get errors
$errors = $validator->errors('errors');
}
}
$recent_posts = $news->get_latest_news();
$this->request->response = $view;
}
}
application / views / news.php
<?php if ($errors): ?>
<p>Errors:</p>
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error ?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
<?php echo Form::open() ?>
<dl>
<dt><?php echo Form::label('title', 'title') ?></dt>
<dd><?php echo Form::input('title', $validator['title']) ?></dd>
<dt><?php echo Form::label('post', 'post') ?></dt>
<dd><?php echo Form::input('post', $validator['post']) ?></dd>
</dl>
<?php echo Form::submit(NULL, 'Post') ?>
<?php echo Form::close() ?>
<?php if ($recent_posts): ?>
<ul>
<?php foreach ($recent_posts as $post): ?>
<li><?php echo $post['title'] . ' - ' . $post['post'];?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
To get this code working in a default install, you would have to enable the database module and configure it for authentication. Then you can access it from index.php/news using default configuration.
It is tested in Kohana 3.0.7 and should give you a good starting point of how you might lay out code. Unlike other frameworks, Kohana seems to be very open ended as to where you put your logic so this is just what made sense to me. If you want to use the ORM instead of rolling your own database interaction, it has its own syntax for validation which you can find here
An example of KO3 validation used with ORM models. Example was posted with permission by a1986 (blaa) in #kohana (freenode).
<?php defined('SYSPATH') or die('No direct script access.');
class Model_Contract extends ORM {
protected $_belongs_to = array('user' => array());
protected $_rules = array(
'document' => array(
'Upload::valid' => NULL,
'Upload::not_empty' => NULL,
'Upload::type' => array(array('pdf', 'doc', 'odt')),
'Upload::size' => array('10M')
)
);
protected $_ignored_columns = array('document');
/**
* Overwriting the ORM::save() method
*
* Move the uploaded file and save it to the database in the case of success
* A Log message will be writed if the Upload::save fails to move the uploaded file
*
*/
public function save()
{
$user_id = Auth::instance()->get_user()->id;
$file = Upload::save($this->document, NULL, 'upload/contracts/');
if (FALSE !== $file)
{
$this->sent_on = date('Y-m-d H:i:s');
$this->filename = $this->document['name'];
$this->stored_filename = $file;
$this->user_id = $user_id;
}
else
{
Kohana::$log->add('error', 'Não foi possível salvar o arquivo. A gravação da linha no banco de dados foi abortada.');
}
return parent::save();
}
/**
* Overwriting the ORM::delete() method
*
* Delete the database register if the file was deleted
*
* If not, record a Log message and return FALSE
*
*/
public function delete($id = NULL)
{
if (unlink($this->stored_filename))
{
return parent::delete($id);
}
Kohana::$log->add('error', 'Não foi possível deletar o arquivo do sistema. O registro foi mantido no banco de dados.');
return FALSE;
}
}
Here's a simple example that works for me.
In my model (client.php):
<?php defined('SYSPATH') or die('No direct script access.');
class Client_Model extends Model {
public $validation;
// This array is needed for validation
public $fields = array(
'clientName' => ''
);
public function __construct() {
// load database library into $this->db (can be omitted if not required)
parent::__construct();
$this->validation = new Validation($_POST);
$this->validation->pre_filter('trim','clientName');
$this->validation->add_rules('clientName','required');
}
public function create() {
return $this->validation->validate();
}
// This might go in base Model class
public function getFormValues() {
return arr::overwrite($this->fields, $this->validation->as_array());
}
// This might go in base Model class
public function getValidationErrors() {
return arr::overwrite($this->fields, $this->validation->errors('form_errors'));
}
}
?>
In my controller (clients.php):
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Clients_Controller extends Base_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$content = new View('clients/read');
$content->foobar = 'bob.';
$this->template->content = $content;
$this->template->render(TRUE);
}
/* A new user signs up for an account. */
public function signup() {
$content = new View('clients/create');
$post = $this->input->post();
$client = new Client_Model;
if (!empty($post) && $this->isPostRequest()) {
$content->message = 'You submitted the form, '.$this->input->post('clientName');
$content->message .= '<br />Performing Validation<br />';
if ($client->create()) {
// Validation passed
$content->message .= 'Validation passed';
} else {
// Validation failed
$content->message .= 'Validation failed';
}
} else {
$content->message = 'You did not submit the form.';
}
$contnet->message .= '<br />';
print_r ($client->getFormValues());
print_r ($client->getValidationErrors());
$this->template->content = $content;
$this->template->render(TRUE);
}
}
?>
In my i18n file (form_errors.php):
$lang = Array (
'clientName' => Array (
'required' => 'The Client Name field is required.'
)
);
I have a brief write up with how to handle this at the link below since it took me a while to figure out and I couldn't find a single good example.
http://www.matt-toigo.com/dev/orm_with_validation_in_kohana_3

Categories