Simple form without model in CakePHP - forms

I'm trying to add form for request of additional information in product page. It's simple form with name, country, email and question fields.
I founded this tutorial , but i don't like idea that just for small form I need make new model and controller.
So i add form in view.ctp
print $this->Form->create('', array('action' => 'sendemail'));
print $this->Form->input('name',array('label' => __('Name',true).':'));
print $this->Form->input('country',array('label' => __('Country',true).':'));
print $this->Form->input('email',array('label' => __('E-mail',true).':'));
print $this->Form->input('question',array('type' => 'textarea', 'label' => __('Your question',true).':'));
print $this->Form->end(__('Send', true));
and add function sendemail in products_controller.php
function sendemail(){
if(!empty($this->data)){
if($this->data['Product']['name'] && $this->data['Product']['country'] && $this->data['Product']['email'] && $this->data['Product']['question']){
// sending email
$this->Session->setFlash(__('Thanks, your qustion was send.', true), 'default', array('class' => 'message status'));
$this->redirect($this->referer());
} else {
// validation
$this->Session->setFlash(__('Fill all fiels', true), 'default', array('class' => 'message error'));
$this->redirect($this->referer());
}
} else {
$this->Session->setFlash(__('Error occurred', true), 'default', array('class' => 'message error'));
$this->redirect($this->referer());
}
}
So is there any way how to validate the form properly and if some field isn't fill after redirection this field will be set as error form input? Also how can I set all already filled fields back to form?
Thanks for any help!

You don't need a database table, but CakePHPs validation support is inherently tied to models. Your code is going to be a lot cleaner than any alternative by creating a dummy model and storing your validation rules in it.
To get around using a table, add var $useTable = false; to your model definition.
To validate without saving, call $this->MyModel->set($this->data); and then a call to $this->MyModel->validates() will perform the check and populate $this->MyModel->validationErrors for automagic population in the form.

Related

CakePHP - Model validation does not work

again alot of similar questions out there but none of them really help me.
HTML5 form validation seems to be triggering with messages "Please fill in this field" instead of the model validation messages which should be "Please enter the model"
I have a form to add Computers to the database.
Here is my form:
echo $this->Form->create('Computer');
echo $this->Form->input('Computer.model', array('label' => 'Model'));
echo $this->Form->input('Computer.memory', array('label' => 'memory'));
echo $this->Form->input('Computer.hdd', array('label' => 'hdd'));
echo $this->Form->input('Computer.price', array('label' => 'price'));
echo $this->Form->end('Save Computer');
Here is the full controller code with index and add actions
<?php
class ComputersController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function index() {
$this->set('computers', $this->Computer->find('all'));
}
public function add() {
if ($this->request->is('post')) {
if (!empty($this->request->data)) {
$this->Computer->save($this->request->data);
$this->Session->setFlash(__('Your Computer has been saved, or so it seems.....'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Not sure why we got here 1.'));
} else {
$this->Session->setFlash(__('By right, this should be the index page'));
}
}
}
?>
Here's the model
<?php
class Computer extends AppModel {
public $validate = array(
'model' => array(
'Please enter model name'=> array(
'rule'=>'notEmpty',
'message'=>'Please enter model'
)
)
);
}
?>
I read from other forms that triggering the model save function, which I do, will automatically trigger the model validation. How can i get the model validation to work?
Thanks
Kevin
As you were saying, if you have the notEmpty validation in the model, CakePHP adds required="required" on the input attributes. This is handled by the browser, so you see the default Please enter this field message when you try to submit an empty value. An advantage is that if you are using the browser in a different language, the message will be displayed in that language.
If you want to change that message, you can try a solution like the ones from this question. (this is probably not what you want)
If you want to remove that client-side message, you can disable it using novalidate
echo $this->Form->create('Computer', array('novalidate' => 'novalidate'));
This way, the HTML5 required property will be ignored, and you will get the message from the model.
I am not sure if there is a way to tell Cake to use the server-side value on the client.
$this->{Model}->save() returns false if the validation fails, but in your case you're redirecting with a flash message after save function. so first check the form is saving perfectly or not, if perfectly saving then redirect to listing page other wise render your view file with a flash message where you can view the validation messages.
if ($this->Computer->save($this->request->data)) {
$this->Session->setFlash(__('Your Computer has been saved, or so it seems.....'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to save form'));
}
Note: To disable html validation just do
$this->Form->inputDefaults(array(
'required' => false
));
in your view file
Hope this helps you.
Set 'novalidate' => true in options for FormHelper::create()
echo $this->Form->create('Computer', array('novalidate' => true));
For more information, go to http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html

Drupal 7: Show fields on a form based on another field and a database lookup

I have a form I created in a custom module using the Form API. It is a fairly basic form with only 4 fields. It basically signs a user up for a job alert system. We are basing it only by email address with a few search parameters. We want people to be able to setup a search agent quickly and anonymously meaning they will NOT be creating a Drupal user account as we don't want them to have to deal with a password etc. They will just put in their email address, check off a few preferences and we will save the data.
Now the issue I need to deal with is allowing the user to edit their preferences later on and/or unsubscribe. Again this is not high security and it doesn't need to be. What I would like to do is initially ask ONLY for their email address in the form and allow them to submit it. I would then check the database to see if we already have an entry for that email address and if so, display the pre-filled form for them to edit or unsubsribe, other wise just show them the blank form. So I am just trying to figure out the best way to go about this. I'm thinking I just have one form with all of the fields including email address, but somehow only display the other fields besides the email address after a successful call to the database. I'm just tripping up on how to accomplish this.
EDIT:
I'm wondering if I can use Drupal's AJAX functionality to accomplish this? I tried this, but I couldn't get it to work. I put an Ajax attribute on my submit button with a wrapper ID and a callback function. I created a form element in my form with blank markup and used a prefix and suffix that created a wrapper div with the ID I used in my AJAX parameter. Then I am thinking in my callback function I can do the database lookup and then return the form elements I need either pre-filled or not into the wrapper div that was created, but when I do this, the form does submit via AJAX and I get the spinning wheel, but no matter what I return in my callback, it does not appear in my output wrapper div. Am I going about this the right way? I also made sure I have $form_state['rebuild'] = TRUE; on my original form.
Here is what I tried and it didn't work.
/**
* Implements hook_form().
*/
function _vista_form($form, &$form_state) {
$form = array();
$form_state['rebuild'] = TRUE;
$form['email'] = array(
'#type' => 'textfield',
'#title' => 'Email',
'#required' => TRUE,
);
$form['render_area'] = array(
'#type' => 'markup',
'#markup' => '',
'#prefix' => '<div id="job-agent-form">',
'#suffix' => '</div>',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#attributes' => array('class' => array('submit')),
'#ajax' => array(
'callback' => '_display_form',
'wrapper' => 'job-agent-form',
'method' => 'replace',
'effect' => 'fade',
),
return $form;
}
function _display_form($form, &$form_state) {
// there are other form elements that would go here also, I just added two for example
$type_options = array(
'VISTA-HealthCare-Partners-Government' => 'Vista Healthcare Partners',
'International' => 'International Locum Tenens',
'Permanent' => 'Permanent Physician',
'US-Locum-Tenens' => 'US Locum Tenens',
);
$form['job_type'] = array(
'#type' => 'checkboxes',
'#multiple' => TRUE,
'#title' => 'Type of Job',
'#options' => $type_options,
'#empty_option' => 'Choose a placement type',
'#empty_value' => 'all',
//'#default_value' => $type_selected,
);
$form['active'] = array(
'#type' => 'checkbox',
'#title' => 'Subscribe/Unsubscribe',
'#default_value' => 1,
);
return $form;
}
I would go for creating all fields in the form than use hook_form_alter() to hide the unneeded ones with ['#access'] = FALSE.

$this->request->data EMPTY - When I have disabled Fields CakePHP 2

I have a form which has some disabled fields, when the form is submitted both $this->request->data and $_POST is empty, removing the disabled fields and it is fine again. I would have though it would still pass though the non-disabled fields. I've even tried to remove the disabled field attribute when the submit button is pushed but this still returns an empty array.
Is there something cake related that might be causing this?
Thanks
// SNIPPET FROM THE VIEW CODE:
$this->Form->create('Card', array('class' => 'GeneralValidate'));
$this->Form->input('Card.property_id', array('type'=>'select', 'empty'=>true , 'class' => 'required adminOnlyField', 'div' => array('class' => 'required')));
$this->Form->input('Card.building_id', array('type'=>'select', 'empty'=>true, 'id' => 'BuildingSelector', 'class' => 'adminOnlyField', 'label' => 'Building (If Applicable)'));
$this->Form->input('Prospect.waiting_list_details', array('value' => $prospect['Prospect']['waiting_list_details']));
$this->Form->input('SaleDetail.property_sold', array('class' => 'checkbox', 'checked' => $ps_checked));
$this->Form->input('SaleDetail.date_conditions_met', array('type'=>'text', 'class' => 'text date_picker adminOnlyField', 'value' => $this->Date->format($saledetail['SaleDetail']['date_conditions_met'])));
$this->Form->button('Save & Continue', array('type'=>'submit', 'label' => 'Save', 'name' => 'quicksave' , 'class' => 'submit long clear_ready_only'));
// JS FROM THE VIEW
$(function () {
var $adminOnly = $('.adminOnlyField');
$adminOnly.prop('disabled',true).prop('readonly',true);
$adminOnly.attr("onclick","return false");
$adminOnly.attr("onkeydown","return false");
$adminOnly.removeClass('required');
$adminOnly.removeClass('date_picker');
$('.clear_ready_only').click(function(e)
{
e.preventDefault();
$adminOnly.prop('disabled',false).prop('readonly',false);
$adminOnly.attr("onclick","return true");
$adminOnly.attr("onkeydown","return true");
$('#CardModifysaleForm').submit();
});
});
That's the way HTML works, disabled don't get posted. CakePHP can't change what is sent from the browser. If you still want the value you can set it as a hidden element.
Update
Some problems I see:
Missing Form::end() in view (always a good idea to insert it).
You never said your form was submitted from JS, first test with a simple form POST then JS.
Your JS code is set to submit a form by ID CardModifysaleForm. There's no such ID in your supplied view code and you're not setting your form to that ID from the snippet you supply.
I ended up removing the disabled option from this, leaving the ready only and added some addition CSS stylings so it looked disabled to the user. This is not the exact answer to the question but works as a different approach.

Zend form in a popup (fancybox, lightbox....)

I am developping a web application using Zend and I ran out of ideas for a problem I am having. In just a few words, I am trying to have a contact form in a popup (Fancybox, lightbox, colorbox or whatever...). The whole thing works fine, in the sense that it shows up the contact form in the popup and allows to send emails. However, whenever there are errors (unfilled input or filled wrong), I couldn't get those errors to be displayed on the popup (it actually redirects me back to the form in a normal display (view+layout), to show the errors.
It is perhaps possible but I now thought that perhaps I could more easily bring my error message to a new popup (the contact page, filled unproperly, would lead to a error popup page...). I think this alternative could look cool but am having real trouble doing it. Now my real question is : Can we really make a form on a popup, using Facybox (Lighbox or any other actually ... just want my popup) and Zend? Any Guru outhere??
Thanks a lot
here is the code:
the link for instance:
<a class="popLink" href=" <?php echo $this->url(array('module'=>'default', 'controller'=>'contact', 'action'=>'sendmail')).'?ProID='.$this->proProfil->getProID(); ?>">Contact</a>
the action:
public function sendmailAction()
{
$this->_helper->layout()->setLayout('blank');
$request = $this->getRequest();
$proID = $this->_getParam("ProID");
$professionalsList = new Model_DirPro();
$proName = $professionalsList->getProInfo($proID);
$translate = Zend_Registry::get('translate');
Zend_Validate_Abstract::setDefaultTranslator($translate);
Zend_Form::setDefaultTranslator($translate);
$contactform = new Form_ContactForm();
$contactform->setTranslator($translate);
$contactform->setAttrib('id', 'contact');
$this->view->contactform = $contactform;
$this->view->proName = $proName;
if ($request->isPost()){
if ($contactform->isValid($this->_getAllParams())){
$mailSubject = $contactform->getValue('mailsubject');
if ($contactform->mailattcht->isUploaded()) {
$contactform->mailattcht->receive();
//etc....
the form:
class Form_ContactForm extends Zend_Form
{
public function init ()
{
$this->setName("email");
$this->setMethod('post');
$this->addElement('text', 'mailsubject',
array('filters' => array('StringTrim'),
'validators' => array(), 'required' => true, 'label' => 'Subject:'));
$mailattcht = new Zend_Form_Element_File('mailattcht');
$mailattcht->setLabel('Attach File:')->setDestination(APPLICATION_PATH.'/../public/mails');
$mailattcht->addValidator('Count', false, 1);
$mailattcht->addValidator('Size', false, 8000000);
$mailattcht->addValidator('Extension', false,
'jpg,png,gif,ppt,pptx,doc,docx,xls,xslx,pdf');
$this->addElement($mailattcht, 'mailattcht');
$this->addElement('textarea', 'mailbody',
array('filters' => array('StringTrim'),
'validators' => array(), 'required' => true, 'label' => 'Body:'));
$this->addElement('submit', 'send',
array('required' => false, 'ignore' => true, 'label' => 'Send'));
$this->addElement('hidden', 'return', array(
'value' => Zend_Controller_Front::getInstance()->getRequest()->getRequestUri(),
));
$this->setAttrib('enctype', 'multipart/form-data');
}
}
I would suggest implementing AJAX validation. This would allow for the form to be verified before it is submitted. ZendCasts has a good tutorial on how to accomplish this: http://www.zendcasts.com/ajaxify-your-zend_form-validation-with-jquery/2010/04/
Ajax requests are handled via the contextSwitch action helper. You can to specify the various contexts an action needs to handle (xml or json) in the init method of the controller as follows:
public function init()
{
$this->_helper->contextSwitch()
->addActionContext('send-mail', 'json')
->initContext()
;
}
The request url should contain a "format=json" appended to the query string. This will execute the action and send the response in json format. The default behaviour of JSON context is to extract all the public properties of the view and encode them as JSON. Further details can be found here http://framework.zend.com/manual/en/zend.controller.actionhelpers.html
I found a "probably not the prettiest" working solution, it is to indeed use ajax as mentioned in the previous zendcast for validation to stop the real validation (preventdefault), process the data return the result and if everything's ok restart it.

Arbitrary Form Processing with Drupal

I am writing a module for my organization to cache XML feeds to static files to an arbitrary place on our webserver. I am new at Drupal development, and would like to know if I am approaching this the right way.
Basically I:
Expose a url via the menu hook, where a user can enter in a an output directory on the webserver and press the "dump" button and then have PHP go to drupal and get the feed xml. I don't need help with that functionality, because I actually have a prototype working in Python (outside of Drupal)..
Provide a callback for the form where I can do my logic, using the form parameters.
Here's the menu hook:
function ncbi_cache_files_menu() {
$items = array();
$items['admin/content/ncbi_cache_files'] = array(
'title' => 'NCBI Cache File Module',
'description' => 'Cache Guide static content to files',
'page callback' => 'drupal_get_form',
'page arguments' => array( 'ncbi_cache_files_show_submit'),
'access arguments' => array( 'administer site configuration' ),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
I generate the form in:
function ncbi_cache_files_show_submit() {
$DEFAULT_OUT = 'http://myorg/foo';
$form[ 'ncbi_cache_files' ] = array(
'#type' => 'textfield',
'#title' => t('Output Directory'),
'#description' => t('Where you want the static files to be dumped.
This should be a directory that www has write access to, and
should be accessible from the foo server'),
'#default_value' => t( $DEFAULT_OUT ),
'#size' => strlen( $DEFAULT_OUT ) + 5,
);
$form['dump'] = array(
'#type' => 'submit',
'#value' => 'Dump',
'#submit' => array( 'ncbi_cache_files_dump'),
);
return system_settings_form( $form );
}
Then the functionality is in the callback:
function ncbi_cache_files_dump( $p, $q) {
//dpm( get_defined_vars() );
$outdir = $p['ncbi_cache_files']['#post']['ncbi_cache_files'];
drupal_set_message('outdir: ' . $outdir );
}
The question: Is this a decent way of processing an arbitrary form in Drupal? I not really need to listen for any drupal hooks, because I am basically just doing some URL and file processing.
What are those arguments that I'm getting in the callback ($q)? That's the form array I guess, with the post values? Is this the best way to get the form parameters to work on?
Thanks for any advice.
You can process forms in two stages, validate and submit.
Validate is for when you want to validate some user provided and raise form errors if some user input was invalid (like an invalid url or email address)
Submit which is the one you use is called if a form passes all of its validations, so at that point if you made a proper validation you will know that the data supplied by the user is okay.
Your submit function should look like this:
function ncbi_cache_files_dump(&$form, &$form_state) {
// $form: an array containing the form data
// $form_state: data about the form, like the data inputted in the form etc.
// code...
}
I think you need 2 separate forms here:
for setting the directory (the one you have now);
for making a dump (another form that would use the configured path).
Also it seems logical to publish the previously saved path as the default value in the settings form (instead of a hard-coded path).
And in general you should check the form input data from the second parameter of the submit callback:
function ncbi_cache_files_dump(&$form, &$form_state) {
$outdir = $form_state['values']['ncbi_cache_files'];
// ...
}