can i pass form dropdown value in my controller and after this, i can send the value in my DB table....please help me i m new in cakephp here is my job_content.ctp
echo'<div class="AcceptButtonFormData">';
echo $this->Form->create('Job' ,array('action' => 'view'));
$ipr_value=array('0'=>0.0,'1'=>.1,'2'=>.2,'3'=>.3);
echo $this->Form->input('IPR_teeth_pair12',array('type' => 'select','name'=>'drop12', 'options' => $ipr_value,'default'=>0));
echo $this->Form->input('IPR_teeth_pair23',array('type' => 'select','name'=>'drop23', 'options' => $ipr_value,'default'=>0));
echo $this->Form->input('IPR_teeth_pair34',array('type' => 'select','name'=>'drop34', 'options' => $ipr_value,'default'=>0));
echo $this->Form->end();
echo '</div>'
yes you can save it. As per above form this will post to you controller action in view
public function view() {
// Has any form data been POSTed?
if ($this->request->is('post')) {
// If the form data can be validated and saved...
if ($this->Job->save($this->request->data)) {
// Set a session flash message and redirect.
$this->Session->setFlash('JobSaved!');
$this->redirect('/jobs');
}
}
// If no form data, find the recipe to be edited
// and hand it to the view.
$this->set('jobs', $this->Job->findAll());
}
below is just sudo code you can change as per you need and for more understanding you can visit cakephp.org
Related
For example we have this ActiveForm implementation in a sample view:
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'first_name')->textInput(['maxlength' => true]); ?>
<?=$form->field($model, 'last_name')->textInput(['maxlength' => true]); ?>
<div id="additional-form-fields"></div>
<a href="#" id="load-additional-form-fields">
Load more fields
</a>
<?php ActiveForm::end(); ?>
Now, I want to add more ActiveField / ActiveForm fields inside this form and place them in the #additional-form-fields element with Ajax, I'd do a simple jQuery callback:
$('#load-additional-form-fields').click(function() {
$.get('/site/additional-fields', {}, function(data) {
$('#additional-form-fields').html( data );
});
});
And the action additional-fields inside SiteController would be something as:
public function actionAdditionalFields() {
$model = new User;
return $this->renderAjax('additional-fields', [
'model' => $model,
// I could pass a 'form' => new ActiveForm, here, but it's a big NO-NO!
]);
}
And this works perfectly, only if I don't use any other ActiveField fields inside this action's view:
<?=$form->field($model, 'biography')->textInput(['maxlength' => true]); ?>
<?=$form->field($model, 'country')->textInput(['maxlength' => true]); ?>
<?=$form->field($model, 'occupation')->textInput(['maxlength' => true]); ?>
Of course, I have to pass or instatiate $form somehow in this view, but it's NOT an option to use another ActiveForm::begin() / ActiveForm::end() anywhere inside this view since it will create another <form> tag and thus when I inject the Ajax response, I'll end up with with a <form> inside a <form> ...
Now, my question is as follows: Since I want to use ActiveForm, how can I share an instance of the ActiveForm through out multiple requests?
Is it doable / possible, if so, please help me realize how?
So far I have tried to put $form inside a session, but that's definitelly not working and not an option. Different than that, I've tried when passing parameters to renderAjax:
[
'model' => $model,
'form' => new ActiveForm,
]
In this case I get the following:
Form fields are created as they should with appopriate names and id's.
jQuery is loaded again (at the bottom of the response: <script src="..."> ... you get the idea)
I don't get the generated JavaScript for validation.
Is there anyway to share an instance of $form?
Okay, I have manage to do this, so I'll post the solution here and I'll open an issue on Github - might be useful in future versions.
1. Updates in yii2\widgets\ActiveForm.php
I've added a following property to the ActiveForm class:
/**
* #var boolean whether to echo the form tag or not
*/
public $withFormTag = true;
And I've changed run() method into this (check for // <-- added):
public function run()
{
if (!empty($this->_fields)) {
throw new InvalidCallException('Each beginField() should have a matching endField() call.');
}
$content = ob_get_clean();
if($this->withFormTag) { // <-- added
echo Html::beginForm($this->action, $this->method, $this->options);
} // <-- added
echo $content;
if ($this->enableClientScript) {
$id = $this->options['id'];
$options = Json::htmlEncode($this->getClientOptions());
$attributes = Json::htmlEncode($this->attributes);
$view = $this->getView();
ActiveFormAsset::register($view);
$view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
}
if($this->withFormTag) { // <-- added
echo Html::endForm();
} // <-- added
}
Thus if we instantiate a form like this:
$form = ActiveForm::begin([
'withFormTag' => false,
]);
It will not echo a <form> tag, but will render all ActiveField items and it will create their respective JavaScript/jQuery validators if $this->enableClientScript = true;.
2. Updates in my local view/file
After applying the previous fix in the base class, I needed to do the following in my view:
<?php $form = ActiveForm::begin([
'withFormTag' => false,
'id' => 'w0',
]); ?>
I had to pass the id parameter since every next instance of the ActiveForm class is incremented by 1, and I want my JavaScript/jQuery validators to be applied to the parent form, which by default starts from 0 -> w0.
And this is what did the trick!
Here's the Github issue as well: https://github.com/yiisoft/yii2/issues/12973
I have created a form which I need to validate using model and controller .Here is my form
index.ctp
<?php echo $this->Form->create('Contact',array('url'=>array('controller'=>'contacts','action'=>'add')));
echo $this->Form->text('name');
Model : Contact.php
class Contact extends AppModel
{
var $name = 'Contact';
var $useTable = false;
public $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false,
'message' => 'Letters and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
)
);
}
Controller : ContactsController.php
public function add()
{
$this->Contact->validates();
$this->request->data['Country']['country_name']=$this->request->data['Contact']['country'];
$this->Country->saveall($this->request->data);
$this->redirect('/Contacts/index/');
}
I am trying to do the validation by googling but it seems difficult to me so if anyone could describe the process it would be a great help .My cakephp version is 2.3.8. I just need to validate this name field , as when I click in submit it will show this message in the form.
Your controller code should be like this
The process of validation in CakePHP is like
1) as you have defined validation rules in CakePHP model public `$validates = array();`
2) when ever you do a save on particular model directly or through any association
a callback method beforeValidate for that model gets called to validate the data which is being saved.
3) once the data is validated then beforeSave callback is called after this save method is called.
4) we can also validate the form input fields in controller using $this->Model->validates() but then while saving we have to disable the beforeValidate callback by doing
$this->Model->save($data,array('validate'=>false));
Otherwise you will end validating the same data twice
your controller code should be somewhat like this.
public function add() {
// here we are checking that the request is post method
if ($this->request->is('post')) {
$this->request->data['Country']['country_name']
= $this->request->data['Contact']['country'];
// here we are saving data
if ($this->Contact->saveAll($this->request->data)) {
//here we are setting a flash message for user
$this->Session->setFlash('your record has been added','success');
$this->redirect(array('controller'=>'contacts','action' => 'index'));
} else {
//here we are setting a flash message for user for error if input are not
//validated as expected
$this->Session->setFlash('sorry we could add your record','error');
}
}
}
For more information you can always refer to http://book.cakephp.org/2.0/en/models/callback-methods.html
I don't want to use the FormHelper from CakePHP, because I want to use some Ajax in my app.
How can I pass the data from the form to the Controller? I'm using $.post from jQuery but I always get an error.
Thanks!
You can use Ajax with the CakePHP Form Helper.
In your view file .ctp put:
echo $this->Form->create('Model', array('id'=>'YourFormId', array('default'=>false)));
echo $this->Form->input('field');
echo $this->Form->submit('Save');
echo $this->Form-->end
Notice in your form->create your passing a default=>false which tells the form to not do a normal "Submit".
At the bottom of your view file .ctp put:
$data = $this->Js->get('#YourFormId')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourFormId')->event(
'submit',
$this->Js->request(
array('action' => 'yourAction', 'controller' => 'yourController'),
array(
'update' => '#flash',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
)
);
echo $this->Js->writeBuffer();
The above is CakePHP JS helper to help you write Ajax and Javascript which PHP. It basically grabs the form data that is being submitted and serializes it and passed it to /yourcontroller/youraction via ajax. The update=>#flash is telling Cake to Update the #flash div after the action is done.
Remember in your Controller to have public
public $helpers = array('Js');
public $components = array('RequestHandler');
-- jQuery --
$.post('<?=$this->Html->url(array('controller'=>'xxx','action'=>'yyy'))?>', {a:1,b:2});
-- cakePHP --
function yyy() {
$a = $this->request->data['a'];
$b = $this->request->data['b'];
}
I'm new to cakePHP and I've made a simple form following some tutorial. On this html form I've used validation. Now the problem is that the validation is working but the message is not displaying what I want it to display. I tried the code below.
Model
public $validate = array(
'title' => array(
'title_required' => array(
'rule' => 'notEmpty',
'message' => 'This is required field'
),
'title_unique' => array(
'rule' => 'isUnique',
'message' => 'This should be unique title'
)
)
);
Controller
public function add() {
if ($this->request->data) {
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Post has been added successfully');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Error occured, Please try agan later!');
}
}
}
View
<h2>Add New 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');
?>
The validation error which I've seen is not the message I mentioned in my controller.
That's built-in browser validation.
Since 2.3 the HTML5 required attribute will also be added to the input based on validation rules.
Your title has the notEmpty rule, so Cake is outputting
<input type="text" required="required" ..
and your browser is triggering that message.
Edit: to override this behaviour, you can do:
$this->Form->input('title', array('required'=>false));
or
$this->Form->submit('Submit', array('formnovalidate' => true));
When you submit the form, your model validation will fire.
From your code what i can see is that you havent included helpers.
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
Just add to your controllers and try..
Your Form-create() options are invalid, first argument is the model-name, second is for options:
<h2>Add New 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');
?>
If the form-helper does not know which 'model' it is creating a form for, I won't check for field validation in the right place, hence, it won't output the validation errors for 'title'
[update] solution above didn't solve the problem. OP has modified the question
Some ideas:
Be sure to enable 'debug' (App/Config/core.php set Configure::write('debug', 2); Otherwise CakePHP may be using a 'cached' version of your model.
If you've named your Model incorrectly, Cake may be automatically generating a model for you, in which case your own model is never actually used, try this for debugging to see if we even 'get' to your model:
Add this to your model;
public function beforeValidate($options = array())
{
debug($this->data); exit();
}
I am using $this->Js->submit to pass a value to my controller asynchronously and than update a div (id = #upcoming). Somehow I cannot save/retrieve the value of the field 'test' which is passed to my controller. Firebug tells me that the correct value is passed. What am I doing wrong?
View file (playlist.ctp):
echo $this->Form->create('Add', array('url' => array('controller' => 'Gods', 'action' => 'add')));
echo $this->Form->input('test');
echo $this->Js->submit('Addddd', array(
'url' => array(
'controller' => 'Gods',
'action' => 'add'
),
'update' => '#upcoming'
));
echo $this->Form->end();
echo $this->Js->writeBuffer(array('inline' => 'true'));
Controller action:
public function add()
{
$this->autoLayout = false;
$this->layout = 'ajax';
$link = $this->request->data['Add']['test'];
$this->set('test',$link);
}
And its view file (add.ctp):
<?php
echo $test;
?>
Thanks for your help!
have you tried pr($link) in the controller method? Or just send it to a log file if you prefer that. That way you can see if the data is received.
If so, I think there is nothing returned because of
$this->autoLayout = false;
Try it without this. It will still call the ajax layout instead of the default.
Otherwise you have to manualy call the render function
$this->render('add');
EDIT
As explained in the comments below, make sure your views are in the right place. (that would be the view folder associated with the controller)