I am a new cake php developer.I am trying to insert multiple record but i cant.My table Structure is given below:
Table Name :
agents
==============================================
id | Contact | Name | email_add | Address
==============================================
Controller Code :
public function send_money()
{
$this->layout='agent';
$this->Agent->create();
$this->Agent->set($this->data);
if(empty($this->data) == false)
{
if($this->Agent->save($this->data))
{
$this->Session->setFlash('Information Added Successfully.');
$this->redirect('send_money');
}
}
else
{
$this->set('errors', $this->Agent->invalidFields());
}
}
Model Code Is :
<?php
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class Agent extends AppModel
{
public $name='Agent';
public $usetables='agents';
public $validate = array(
'contact' => array(
'contact_not_empty' => array(
'rule' => 'notEmpty',
'message' => 'Please Give Contact No',
'last' => true
),
),
'name' =>array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Name.'
),
'email_add' => array(
'email_add' => array(
'rule' => 'email',
'allowEmpty' => true,
'message' => 'Please Enter Valid Email',
'last' => true
)),
);
}
?>
Its not possible to insert records with this code.What should I do?
Let me explain everything.
First of all your html form must be looks like following.
<?php echo $this->Form->create('User'); ?>
<tr>
<td>
<?php
echo $this->Form->input('User.0.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.1.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.2.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
</td>
<td>
<input type="submit" value="Add" >
</td>
</tr>
<?php echo $this->Form->end(); ?>
As you can see to save many record at same time using cakephp you must define it as above it will parse input fields as array this is cakephp convention.
I mean User.0.address for first array element
User.1.address for second array element
User.2.address for third array element and so on.
Now.
In Controller file.
<?php
function add()
{
$this->User->saveAll($this->data['User']);
}
And yes here you are done saving multiple record at same time.
I just gave you how cakephp works all you need to do is set above hint as per your need.
Best of luck...
Cheers...
Feel Free to ask... :)
Try this saveall() in your query except save, hope this helps
if($this->Agent->saveall($this->data))
Let me know if it work.
I think this
php echo $this->Form->create('Agents', array('action' => 'send_money'));?>
should be replaced with
php echo $this->Form->create('Agent', array('action' => 'send_money'));?>
and use saveall() in place of save.
Related
Basically i have 3 forms.
I have one action in my form and i want create 3 steps form using session.
I want when i click the next button it validates the form1,if successful then redirects to form2..
like wise for form3 but keep all the data in session and in third step the action goes runs and add all the data to database.
I only need to check conditions from session before my insert goes run in my action addjob.
Plz help me to do this.
My main question is how to get all the post data in one session variable and check step by step before insert..
i am learner in cakephp and i have not enough idea about session.
if you are a expert then plz do this.
public function addjob($id = NULL) {
$this->layout = "layout_registration_old";
$this->loadcategory();
$this->loadcargo();
//$this->loadsubcategory();
$this->getCountries();
$this->getstates();
if ($this->request->is('put') || $this->request->is('post')) {
if (isset($id)) {
$this->Job->id = $id;
} else {
$this->request->data['Job']['status'] = 1;
$this->request->data['Job']['job_type'] = 1; //this is used to update the job type private or public.
$this->Job->create();
}
$this->Job->set($this->request->data);
if ($this->Job->AddEdit()) { // ADDEdit is the validation name in model
if ($this->Job->save($this->request->data['Job'], false)) {
if (isset($id)) {
$this->Session->setFlash(__('Job has been updated sucessfully.'));
} else {
$this->Session->setFlash(__('Job has been added succesfully.'));
}
$this->redirect(array('controller' => 'jobs', 'action' => 'index'));
}
} else {
$errors = $this->Job->validationErrors;
$this->Session->setFlash(__('Please check your entry.'), 'flash_error');
}
}
if (isset($id)) {
$this->request->data = $this->Job->find('first', array('conditions' => array('id' => base64_decode($id))));
}
}
form - 1
<?php echo $this->Form->create('Job', array('url' => array('controller' => 'jobs', 'action' => 'addjob')));?>
<?php echo $this->Form->input('customer_name',array('div' => false, 'label' => false));?>
<?php echo $this->Form->input('customer_no',array('div' => false, 'label' => false));?>
<?php echo $this->Form->input('customer_email',array('div' => false, 'label' => false));?>
<?php
echo $this->Form->input('transport_type', array(
'type' => 'select',
'label' => false,
'class' => 'select',
'options' => array(
1 => 'Road'
),
));
?>
<?php echo $this->Form->submit('Save', array('class' => "navigation_button btn btn-primary btn-sm", 'div' => false)); ?>
<?php echo $this->Form->end(); ?>
form - 2
<?php echo $this->Form->create('Job', array('url' => array('controller' => 'jobs', 'action' => 'addjob')));?>
<?php echo $this->Form->input('fname',array('div' => false, 'label' => false));?>
<?php echo $this->Form->input('lname',array('div' => false, 'label' => false));?>
<?php echo $this->Form->input('email',array('div' => false, 'label' => false));?>
<?php echo $this->Form->submit('Save', array('class' => "navigation_button btn btn-primary btn-sm", 'div' => false)); ?>
<?php echo $this->Form->end(); ?>
form - 3
<?php echo $this->Form->create('Job', array('url' => array('controller' => 'jobs', 'action' => 'addjob')));?>
<?php echo $this->Form->input('shop',array('div' => false, 'label' => false));?>
<?php echo $this->Form->input('business',array('div' => false, 'label' => false));?>
<?php echo $this->Form->input('status',array('div' => false, 'label' => false));?>
<?php echo $this->Form->submit('Save', array('class' => "navigation_button btn btn-primary btn-sm", 'div' => false)); ?>
<?php echo $this->Form->end(); ?>
Instead of saving the data from first 2 forms in a session, you should implement a multi part form using any javascript solution (Form wizard). Validate the data of each step using javascript or via ajax (if needs to be done dynamically) before moving to the next step and submit form at the end so that you don't have to play with sessions.
Example link
PS - This could go as a comment to the question but I haven't gained enough reputations to post comments yet :(
I'm having some issues with a form and it's driving me insane.
Whenever I try to upload an image to my database, I get
Notice: Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1009]
I'm not sure what I'm doing wrong or missing. Any help is appreciated.
This is my Model
'banner_image' => array(
'not_required' => array(
'allowEmpty' => true,
'required' => false,
),
'is_image' => array(
'rule' => 'is_image_check',
'message' => 'We found that the file you uploaded is not an image.',
//'allowEmpty' => false,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
This is my controller
/**
* admin_add method
*
* #return void
*/
public function admin_add() {
if ($this->request->is('post')) {
$this->Survey->create();
if ($this->Survey->save($this->request->data)) {
$this->Session->setFlash(__('The survey has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The survey could not be saved. Please, try again.'));
}
}
}
and this is my form
<?php echo $this->Form->create('Survey', array('type'=>'file')); ?>
<fieldset>
<legend><?php echo __('Admin Add Survey'); ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('subtitle');
if ( empty($this->request->data['Survey']['banner_image']) or isset($this->validationErrors['Survey']['banner_image']) ):
echo $this->Form->input('banner_image', array('type'=>'file'));
else :
echo $this->Html->image('/img/surveys/' . $this->request->data['Survey']['banner_image'] ) ;
echo $this->Html->link('Remove this image?', '/admin/Surveys/remove_image/' . $this->request->data['Survey']['id'] ) ;
endif;
// echo $this->Form->input('listing_image', array('type'=>'file'));
echo $this->Form->input('url_iframe');
echo $this->Form->input('enable');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
This is what your controller receives for field banner_image:
$this->request->data['Survey']['banner_image'] = array(
'name' => 'example_image.jpg',
'type' => 'image/jpg',
'tmp_name' => 'C:/WINDOWS/TEMP/php1EE.tmp', //path will vary on Unix-like OSes
'error' => 0,
'size' => 41737,
);
If you attempt to save this into your table, you will get
Notice: Array to string conversion in filename on line X
Therefore, you have to do some pre-processing before you can call save().
Your surveys.banner_image is probably set to accept a file name.
A typical approach is to implement the Survey::beforeSave() callback and add the necessary code to move the uploaded file from its temporary location to the destination folder of your choice.
You then overwrite the $data['Survey']['banner_image'] array with $data['Survey']['banner_image']['name'].
Or, instead of reinventing the wheel, you can use one of the multiple CakePHP plugins which handles uploads, for example josegonzalez/cakephp-upload.
For further reference, see:
FormHelper::file(string $fieldName, array $options)
I have a form to add a new user. Only an admin who is logged in may access this form. Unfortunately, the username and the password of the admin are filled into the form fields which are expected to be completely clear. And one really strange thing is: The username is printed into the birthday field!
I really cannot explain myself how it works. And I could not found in the WWW any post from a person who has got the same problem - I only found questions and answers about pre-filled form data that is wanted.
This is the View /Users/add.ctp
<h1>Add a new Member</h1>
<?php echo $this->Form->create('User', array('url' => BASE_URL.'/users/add', 'action'=>'post')); ?>
<table class="form">
<tr><td>Username:</td><td><?php echo $this->Form->input('User.username', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Name:</td><td><?php echo $this->Form->input('User.name', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Lastname:</td><td><?php echo $this->Form->input('User.lastname', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>E-Mail:</td><td><?php echo $this->Form->input('User.email', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Birthday:</td><td><?php echo $this->Form->input('User.birth', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Password:</td><td><?php echo $this->Form->input('User.password', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
</table>
<?php
echo $this->Form->submit('Submit', array('formnovalidate' => true));
echo $this->Form->end();
?>
And here is the Controller /UsersController.php
public function add() {
$this->layout = 'admin';
if ($this->request->is('post')) {
// Saving the data
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Data saved.'));
return $this->redirect(array('action' => 'view'));
}
$this->Session->setFlash(__('Data could not be saved.'));
}
}
By the way: Saving works fine.
Of course, the admin is of Object User, as is the new member to be added. I think, here lies the problem, but I really do not know... I am thinking about this problem the whole day :( Does anybody know what to do?
Thanks in advance.
Is not your browser? (saved username/password when you type for the first time)
So, you can turn of the autocomplete.
<?php echo $this->Form->create('User', array('url' => BASE_URL.'/users/add', 'action'=>'post', 'autocomplete' => 'off')); ?>
This option => 'autocomplete' => 'off'
Check your $this->data.
CakePHP autocompletes forms with data found there because it guesses that is data already submitted by the user.
In you example, if you have some value in $this->data['User']['birth'] it should show that value in the Birthday input.
I've read quite some posts about this, but I havn't been able to solve my problem.
When I try to validate my zend form captcha it always fails even with the correct text.
Here is my code:
// where i call my form
public function contactAction()
{
$this->view->form = new Forms_ContactForm();
}
//my form
class Forms_ContactForm extends Twitter_Form
{
public function init()
{
$this->setAction( 'email/email/contact' );
$this->setMethod('post');
$this->addElement('text', 'strFirstName', array(
'required' => true,
'label' => 'Your First Name' ) );
$this->addElement('text', 'strLastName', array(
'required' => true,
'label' => 'your Last Name' ) );
$this->addElement('text', 'strEmail', array( 'validators' => array(
array('EmailAddress') ),
'required' => true,
'label' => 'Your Email' ) );
$this->addElement('textarea', 'strContent', array(
'required' => true,
'label' => 'Your message' ) );
$this->addElement('captcha', 'captcha', array(
'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'name' => 'captchaField',
'captcha' => 'image',
'captchaOptions' => array(
'captcha' => 'image',
'font'=> 'static/font/arial.ttf',
'imgDir'=>'static/img/captcha',
'imgUrl'=> 'static/img/captcha/',
'wordLen' => 5,
'fsize'=>20,
'height'=>60,
'width'=>200,
'gcFreq'=>50,
'expiration' => 300)
));
$this->addElement('submit', 'submit', array('class' => 'Submit') );
}
}
// and my action to send it
public function contactAction()
{
if( $this->_request->isPost() )
{
$objForm = new Forms_ContactForm();
if( $objForm->isValid($_POST) )
{
$arrParams = $this->_request->getParams();
if( $arrParams['strFirstName'] && $arrParams['strLastName'] && $arrParams['strEmail'] && $arrParams['strContent'] )
{
$this->_objEmail = new Zend_Mail();
$this->_objEmail ->setFrom( $arrParams['strEmail'] );
$this->_objEmail ->setSubject( 'C' );
$this->_objEmail ->setBodyHtml( 'Message from: '. $arrParams['strFirstName'] . ' ' . $arrParams['strLastName'] .
'<BR>eMail address: ' . $arrParams['strEmail'] . '<BR><BR>'
. $arrParams['strContent'] );
$this->_objEmail ->addTo( 'mail#gmail.com' );
$this->view->bolSent = $this->_objEmail->send();
}
}
else
$this->view->form = $objForm;
}
}
It seems that in my contactAction, it generates a new captcha code, so that's why it soesnt match with the one I submitted, but I have no idea how to fix it.
Thank you for your time and help !!
Just saw something dodgy : when i dump my $_POST in contact action here is my result :
array
'strFirstName' => string 'fghjfghj' (length=8)
'strLastName' => string 'ffffffff' (length=8)
'strEmail' => string 'fvhkbno#biu.fr' (length=14)
'strContent' => string 'fewfew' (length=6)
'captchaField' => string 'cebfe69ead38dba86a6b557dc8853b24' (length=32)
The captcha I just entered dosent even appear and instead I have the captcha kay !!??
EDIT
thanks again for your replay !!!
Still not there even with your changes but I think I got whats wrong.
Here is my html for the captcha field:
<div class="control-group">
<label class="control-label required" for="captchaField-input">Please enter the 5 letters displayed below:</label>
<div class="controls">
<img width="200" height="60" src="static/img/captcha/ab2d15044a637338064b39cfd2675837.png" alt="">
<input type="hidden" id="captchaField-id" value="ab2d15044a637338064b39cfd2675837" name="captchaField[id]">
<input type="text" value="" id="captchaField-input" name="captchaField[input]">
<input type="text" value="ab2d15044a637338064b39cfd2675837" id="captchaField" name="captchaField">
</div>
</div>
When I have a look at my params sent, here is what I got :
captchaField ab2d15044a637338064b39cfd2675837
captchaField[id] ab2d15044a637338064b39cfd2675837
captchaField[input] 6af7u
It seems that cptchaField overwright [id] and [input]
I feel like I need to remove this captchaField but have no idea how so far !
I could do that with JS but there must be a clean way to do so !
EDIT AGAIN
Im using ajax to submit the form, with serialize. That could be the problem, ill have a look.
EDIT TER
It is not caused by ajax.
If I manually remove the line :
<input type="text" value="ab2d15044a637338064b39cfd2675837" id="captchaField" name="captchaField">
with firebug, everything is normal and the captcha validates well. Now the question is how to remove this line properly...
SOLUTION
After struggling a lot, here is the solution (remove decorator) !
$captcha = new Zend_Form_Element_Captcha('captchaField',
array('label' => "Please enter the 5 letters displayed below:",
'required'=>true,
'captcha' => array(
'captcha' => 'image',
'font'=> 'static/font/arial.ttf',
'imgDir'=>'static/img/captcha',
'imgUrl'=> 'static/img/captcha/',
'wordLen' => 5,
'fsize'=>20,
'height'=>60,
'width'=>200,
'gcFreq'=>50,
'expiration' => 300
)
));
$this->addElement($captcha);
$this->getElement('captchaField')->removeDecorator("viewhelper");
After struggling a lot, here is the solution (I simply had to remove decorator) !
$captcha = new Zend_Form_Element_Captcha('captchaField',
array('label' => "Please enter the 5 letters displayed below:",
'required'=>true,
'captcha' => array(
'captcha' => 'image',
'font'=> 'static/font/arial.ttf',
'imgDir'=>'static/img/captcha',
'imgUrl'=> 'static/img/captcha/',
'wordLen' => 5,
'fsize'=>20,
'height'=>60,
'width'=>200,
'gcFreq'=>50,
'expiration' => 300
)
));
$this->addElement($captcha);
$this->getElement('captchaField')->removeDecorator("viewhelper");
Thanks Haroon for your help and your time :)
I think you code needs to be like the below, i think in the contactAction.php file the public function contactAction() should handle displaying the form and the action when the form has been posted to ) :
//Display the form
$objForm = new Forms_ContactForm();
$this->view->form = $objForm;
//Handle the form, when it has been posted including validation etc
if( $this->_request->isPost() )
{
if( $objForm->isValid($_POST) )
{
//processing logic etc
}
}
Currently your code is generating a new Captcha to confirm against the data input, because you are instantiating the form after the form has been POSTed to. This instantian of the form needs to be done before the form has been posted to, as I have shown in the code example above.
EDIT
Try this:
$captcha = new Zend_Form_Element_Captcha('captchaField',
array('label' => "Please enter the 5 letters displayed below:",
'required'=>true,
'captcha' => array(
'captcha' => 'image',
'font'=> 'static/font/arial.ttf',
'imgDir'=>'static/img/captcha',
'imgUrl'=> 'static/img/captcha/',
'wordLen' => 5,
'fsize'=>20,
'height'=>60,
'width'=>200,
'gcFreq'=>50,
'expiration' => 300
)
));
$this->addElement($captcha);
This new code after the edit works for me using Zend Framework version 1.11.1
What version of Zend Framework are you sing and how is you Captcha being displayed in your view file??
When var dumping our your output, for the captcha elment you should expect something similar to the below where "5g4ef" is the data you inputted into the Captcha input element:
["captchaField"]=> array(2) { ["id"]=> string(32) "88bb26d62e9fa19b67937c35be4a8cc7" ["input"]=> string(4) "5g4ef" }
I'm just starting to use Zend Framework and was following the quick start documentation for the latest version (1.11.10). Everything was going just fine, but when I placed the form code and ran the application, the form did not render. My code is exactly like http://framework.zend.com/manual/en/learning.quickstart.create-form.html
On the view, I can dump the form just fine with var_dump($this->form);
I've tried echo $this->form(), echo $this->form->render(), but nothing appeared... What could it be?
This problem can occur when Zend can't find the template file for an element. Look at following code:
$element->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'directory/_input.phtml'
)
)
));
The file _input.phtml must be in the right folder for this Controller. Otherwise Zend can't find the template for input and can't successfully render your element and will not show anything.
Make sure you pass the form to the view from the controller.
In your action handler:
$this->view->form = $my_form;
In your view:
echo $this->form;
I suspected that this was the cause of your problem because Zend Framework doesn't complain if you try to echo a parameter that doesn't exist. (i.e. echo $this->some_fake_parameter won't do anything)
Ok so i tried your code, and it worked for me no problem.
Here is everything:
Controller
<?php
class IndexController extends Zend_Controller_Action
{
public function myTestAction()
{
$form = new Form_Guestbook();
// ... processing logics
if($this->getRequest()->isPost())
{
if($form->isValid($this->getRequest()->getPost()))
{
var_dump($form->getValues());
}
}
$this->view->assign('form', $form);
}
}
Form
<?php
class Form_Guestbook extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// Add an email element
$this->createElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));
// Add the comment element
$this->addElement('textarea', 'comment', array(
'label' => 'Please Comment:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add a captcha
$this->addElement('captcha', 'captcha', array(
'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 5,
'timeout' => 300
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Sign Guestbook',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
?>
View
<?php echo $this->form->render(); ?>
can be seen on: http://yaconiello.com/index/my-test
If this isnt working for you, you may be having a configuration error.
I had a problem like that (exact same form, since it is eclipse example)
My problem was due to misunderstanding. Since I thought that I have to directly access to the view script. I entered in the browser something like: hostname/application/view/script/something.php
But in zend all accesses should be through public folder. You have to access to the view like this: hostname/app_name/public/guestbook
hope that would help you