Cakephp input box validation on ctp page - php

How do I directly input validation as required into input box on ctp file without going to controller or model in Cakephp?

I would use JQuery, with the Jquery Validaton plugin.
It is rather straight foreward to include and write the scripts for.
In the view (using a Users form view for the example)
<?php
echo $form->create('User', array('id'=>'UserForm'));
echo $form->input('User.name', array('class'=>'required', 'minlength'=>2));
echo $form->input('User.email', array('class'=>'required email'));
echo $form->end('Send');
echo $javascript->codeBlock('$("#UserForm").validate();', array('inline'=>true));
In the layout under the header part
echo $javascript->link('jquery-1.6.2.min.js');
echo $javascript->link('jquery.validate.min.js');
In the user controller
var $helpers = array('Html', 'Form', 'Javascript');
I did testrun the code to confirm it works.

Related

submit form data in database using cakephp

I am using cakephp and I want to insert form data in my database, but I am getting the following error:
Table posts for model Post was not found in datasource default.
How can I save my data to database. And in cakephp how can we send data from controller to model?
// this is my view code
echo $this->Form->create('posts', array('action' => 'Add'));
echo $this->Form->input('title', array('label' => 'Enter your email address:'));
echo $this->Form->end('Add');
// this is my controller code
public function Add() {
$this->request->data['posts']['title'] = $this->request->data["posts"]["title"];
$this->Post->save($this->request->data);
}
Error says that model "Post" is not created. You need to create file PostsTable.php and put it in src/Model/Table folder.
Also just try CakePHP tutorial from CakeBook.

Cakephp none add action forms

I have an index action in one of my controllers.
In this index action i wish to create a "search" form that calls another action within my controller with a post request.
All the documentation i could find on form creation in cakephp is about creating new elements (i.e insert data into a database ) and not actually sending data to another action / function.
here is an example:
<?php echo $this->Form->create('Product'); ?>
<fieldset>
<legend><?php echo __('Søg Produkt'); ?></legend>
<?php
echo $this->Form->input('Search field');
?>
</fieldset>
<?php echo $this->Form->end(__('Søg')); ?>
How would i send the value of my search field to another action? (so it redirects to that action and sends data to it)
Did you try to read the documentation?
$this->Form->create('Product', array('url' => array('action' => 'search');

Multiple _form views on a single create view [Yii]

I'm trying to merge 3 models to create a fourth one. I have model1, model2 and model3 and I want to merge them into modelMaster. I've also created controllers for all of them. When I call modelMaster/create action, I render the modelMaster/create view which renders the modelMaster/_form view. Inside this _form view, I also want to render model1/_form, model2/_form and a CHtml::dropDownList(), wich takes datas from model3. However, this doesn't work. How can I combine these three different views into one another?
If you try to skip the form generate from the _form views and use unique model names, I think you can use this manual: single form with more models
So the generate of the form definition handles always the parent view and the _form's only the inputs
The other way to use single model in views, create a form model by extend CFormModel, and handle the data binding between this model and the wrapped submodels
If you want to nest several forms into one master form you have to adjust the form templates accordingly. All of your modelMaster/create, model1/_form, model2/_form-views create and render a new CActiveForm (and thus several <form> tags).
Since you cannot nest form-elements in html (how should html know which action to pass the data to) you have to avoid this by doing the following:
Extract the inputs of the form you want to nest into a new view, e.g. model1/_formInputs would look like
...
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name');
<?php echo $form->error($model,'name');
...
alter the model1/create and the other views and get a reference to the form created there, by assigning the return of $this->beginWidget to the variable $form (if not already done):
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'foo',
)); ?>
replace the former input fields with
<?php $this->renderPartial('model1/_formInputs', array('form' => $form); ?>
Now, for example the old model1/create-view should work as expected
To get your multi-model-form working you just have to get the reference to the form created in modelMaster/create and use it to renderPartial all */_formInputs you require. Please also remember to include the models for the inputs into the renderPartial-call. So modelMaster/create would look something like:
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'foo',
)); ?>
/* Master Inputs here */
// Rendering other models' inputs
<?php $this->renderPartial('model1/_formInputs', array('form' => $form, 'model' => $model1); ?>
<?php $this->renderPartial('model2/_formInputs', array('form' => $form, 'model' => $model2); ?>
/* Render Form Buttons here */
<?php $this->endWidget(); ?>
Submit with Ajax, in Yii it is easy to do and it will keep things easy to understand in the controllers, each controller will have a save and respond with json to confirm the save. There is already ajax validation.
/**
* Performs the AJAX validation.
* #param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='employee-form')
{
$valid = CActiveForm::validate($model);
if(strlen($valid) > 2) {
echo $valid;
Yii::app()->end();
}
}
}
As you can see I have modified it to return the error if there is one (validate returns [] if it is valid, I should probably check for that instead of strlen >2 ), otherwise let the script continue, in this case it will go to the save function.

how to ajaxify zend_pagination results (already working with partialoop) using jquery

in the controller i have :
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$this->view->posts = $paginator;
in the view's i have some thing like this :
if ($this->posts != null) {?>
<div id="cities_accord" class="news">
<?php echo $this->partialLoop('partials/post-min.phtml', $this->posts); ?>
</div>
<?php echo $this->paginationControl($this->posts,
'Sliding',
'public/pagination_cont.phtml');
}
the partial/post-min.phtml
<?php
$color = array(1=>'spring',2=>'summer',3=>'autumn',4=>'winter');
?>
<div id='<?php echo $color[$this->partialCounter] ?>' class="accordion_post">
<?php
$link = Digitalus_Uri::get(false, false, array('openCity' =>
$this->id));//$color[$this->partialCounter]));
?>
<h1 class="accordion_post_title"><?php echo $this->title ?></h1>
<p><?php echo $this->teaser ?> <i>read more</i></p>
</div>
the pagination_cont.phtml taken from this link zend ( http://framework.zend.com/manual/en/zend.paginator.usage.html )
will show links that will pass params to the controller to fetch the corresponding whole page which is working alright for now
but i want to change this so that i will be able ajaxify the returned ( i.e. only a single paginated value rather than reloading the whole page ) results how can i do that using jquery and what should i change ..
** EDIT: it would be nice to have a fail-save ,if possible, for browsers(users) that disabled javascript to see the same thing by reloading the page (i.e. keeping the current status for if(javascript_not_enabled ))**
This is what I've done in the past.
First, setup the AjaxContext action helper to enable the html context on your controller action.
Add a .ajax.phtml view that just contains the section of markup that may be replaced via AJAX as well as the pagination control links. You can probably just copy this out of your normal view. Replace that section in your normal view with something like
<div id="reloadable-content">
<?php echo $this->render('controller/action.ajax.phtml') ?>
</div>
This will ensure that your initial and any non-AJAX requests will still include the right content. The <div> id is purely for referencing the loadable block in JavaScript.
Also make sure you include your JS file (using headScript) in the normal view only.
Now, in your JS file, unobtrusively add the appropriate event binding to the paginator links. As you'll be replacing the pagination control section in order to reflect the correct current page and other links, it's probably best to do this using the jQuery live binding. I'm also assuming you'll wrap the pagination control with some kind of identifiable element (<div class="pagination-control"> for example)
$('.pagination-control').find('a').live('click', function(e) {
var link = $(this);
$('#reloadable-content').load(link.attr('href'), { format: 'html' });
return false;
});
Keep in mind that in using this method, you will lose the ability to navigate the paged requests using the normal back / forward browser buttons. You will also lose the ability to bookmark pages directly (though you could always provide a permanent link to the current page as part of the AJAX loaded content).
You can use something like the jQuery history plugin if you're really concerned but that will require more client-side work.
Another caveat is that the above will only work with pagination links. If you want to use a form with dropdown page selection, you need to add another event handler for the submission.
GOT IT and big Thanks to #Phil Brown :
in the controller int() change the response type to json
class NewsController extends Zend_Controller_Action
{
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'JSON')
->initContext();
}
// ...
}
public listAtcion() {
// .............
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$post = array();
foreach($paginator as $post ) {
$post[] = $post;
}
$this->view->post = $paginator;
#TODO //add a check here for non-ajax requests (#improvment)
$this->view->posts = $paginator;
}
in one of the views (most probably in the pagination_cont.phtml) on the pagination controller add the ajax links
<?= $this->ajaxLink (
$this->url('cities'=>$this->page_num),array('id'=>'div_id','complete'=>'js_method(json_data)','method'=>post) ,array('format'=>'JSON'));
and add a JavaScript function of js_method(json_data) to modify the div with id = 'div_id' with a json data
function js_method(json_data) {
var content = parse.JSON(json_data);
$('#div_id').html('');
//fill it with the reposnse content some thing like $('#div_id').append(content);
}

To retrieve value from a text box in a form (view) to controller in cake php

How to o retrieve value from a text box in a form (view) to controller in cake php?
Here's an example from the CakePHP book on saving your Model data:
function edit($id) {
//Has any form data been POSTed?
if(!empty($this->data)) {
//If the form data can be validated and saved...
if($this->Recipe->save($this->data)) {
//Set a session flash message and redirect.
$this->Session->setFlash("Recipe Saved!");
$this->redirect('/recipes');
}
}
//If no form data, find the recipe to be edited
//and hand it to the view.
$this->set('recipe', $this->Recipe->findById($id));
}
If your model was Recipe, and your input was named "title", then the value would be in $this->data['Recipe']['title'], if you setup your view like so:
echo $this->Form->create('Recipe');
echo $this->Form->hidden('id');
echo $this->Form->input('title');
echo $this->Form->end('Save Recipe');
So, look here: http://book.cakephp.org/view/1031/Saving-Your-Data
And try to do the Blog tutorial, it might help you get started: http://book.cakephp.org/view/1528/Blog

Categories