In the below code the captcha is coming and after proving we are not robot nothing happened. I have added both public and private key too.
Also, the captcha tool is coming above the header in it if adding any hidden field an error occur.
<html>
<head>
<script src='https://www.g**le.com/recaptcha/api.js'></script>
</head>
<body>
<?php
class ContactPage extends Page
{
private static $db = array(
'TelCustomerSupport' => 'Varchar',
'TelProjectSupport' => 'Varchar',
'OfficeName' => 'Text',
'OfficeStreetAddress' => 'Text',
'OfficeAddressLocality' => 'Text',
'OfficePostalCode' => 'Varchar',
'OfficeMapLink' => 'Text',
'OfficeLatitude' => 'Text',
'OfficeLongitude' => 'Text',
);
public function getCMSFields()
{
$fields = parent::getCMSFields();
// Add extra fields
$fields->addFieldToTab("Root.Main", new TextField('TelCustomerSupport', 'Phone - Customer, Trade & Retail Support'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('TelProjectSupport', 'Phone - Project Support'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeName'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeStreetAddress'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeAddressLocality'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficePostalCode'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeMapLink'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeLatitude'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeLongitude'), "Content");
return $fields;
}
}
class ContactPage_Controller extends NetSuitePage_Controller
{
private static $allowed_actions = array('ContactForm');
// Generate the form
public function ContactForm()
{
// Create fields
$fields = new FieldList(
TextField::create("FirstName")->setTitle(_t('Contact.FIRSTNAME')),
TextField::create("LastName")->setTitle(_t('Contact.LASTNAME')),
EmailField::create("Email")->setTitle(_t('Contact.EMAILADDRESS')),
TextField::create("Phone")->setTitle(_t('Contact.PHONENUMBER')),
DropdownField::create('Iam', _t('Contact.IAMA'), $this->translateNetsuiteConfigArray('Contact', 'Iam')),
TextField::create("SendSubject")->setTitle(_t('Contact.SUBJECT')),
HoneyPotField::create("Subject2")->setTitle('Subject2'),
TextareaField::create("Message")->setTitle(_t('Contact.MESSAGE'))->setColumns(30)->setRows(10)
);
// Create actions
$submitbutton = new FormAction('doContactForm', _t('Contact.SEND'));
$submitbutton->addExtraClass('btn btn-black');
$actions = new FieldList(
$submitbutton
);
$validator = ZenValidator::create();
$validator->addRequiredFields(array('FirstName', 'LastName', 'Email', 'Phone', 'Iam', 'SendSubject', 'Message'));
$validator->setConstraint('FirstName', Constraint_length::create('max', 32));
$validator->setConstraint('LastName', Constraint_length::create('max', 32));
$validator->setConstraint('Phone', Constraint_length::create('min', 7));
$validator->setConstraint('Email', Constraint_type::create('email'));
$validator->setConstraint('Phone', Constraint_type::create('digits'));
print"<div class=\"g-recaptcha\" data-sitekey=\"6LdCAxEUAAAAAHSWL1xulOjZLv-6PPHTSQJdjpEu\"></div>"
$form = new Form($this, 'ContactForm', $fields, $actions, $validator);
$form->addExtraClass('contact-form');
$form->setFormMethod('POST', true);
return $form;
}
// Deal with form submission
public function doContactForm($data, $form)
{
$submission = new ContactFormSubmission();
$form->saveInto($submission);
$submission->write();
$data['path'] = print_r($this->refererTracker->retrieveAll(), true);
$email = new Email();
$email->setTemplate('ContactFormEmail');
$email->populateTemplate($data);
$email->setTo($this->getNetsuiteConfig('Contact', 'Emails'));
$email->setFrom("no-reply#warmup.co.uk");
$email->setSubject('[warmup.co.uk] New contact from the website');
$email->populateTemplate($data);
$email->send();
$post = $this->getNetsuiteConfig('Contact');
$post->firstname = $data['FirstName'];
$post->lastname = $data['LastName'];
$post->email = $data['Email'];
$post->phone = $data['Phone'];
$post->custentity116 = $data['Iam'];
$post->custentitysubject_contact_us = $data['SendSubject'];
$post->custentitymessage_contact_us = $data['Message'];
if(isset($_POST['g-recaptcha-response'])&& $_POST['g-recaptcha-response']){
var_dump($_POST);
$secret = " 6LdCAxEUAAAAAIss47kbDqOWVaf3H2ruMkgddKTa";
$ip = $_SERVER['REMOTE_ADDR'];
$captcha = $_POST['g-recaptcha-response'];
$rsp = file_get_contents("https://www.***.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip$ip");
var_dump($rsp);
$arr = json_decode($rsp,TRUE);
if($arr['success'])
{
// Check for success
if ($this->queueNetSuitePost($post)) {
return $this->redirect(Director::get_current_page()->Link()."?success=1");
}
}
else{
// Redirect back with form data and error message
Session::set('FormInfo.' . $form->FormName() . '.data', $data);
Session::set('FormInfo.'.$form->FormName().'.errors', array());
$form->sessionMessage("Netsuite error", 'bad');
return $this->redirectBack();
}
}
}
// Returns true if form submitted successfully
public function Success()
{
return isset($_REQUEST['success']) && $_REQUEST['success'] == "1";
}
public function getCurrentSubsite()
{
$subsite = Subsite::currentSubsite();
if($subsite) {
return $subsite->Title;
}
return $subsite;
}
}
"print" or "echo" will render immediately. The rest of your code/template won't render until later. If you want to insert html you are better off adding a LiteralField to your form.
What might be even better is using a module which provides recaptcha in an easy to use form field, e.g. https://github.com/Level51/silverstripe-recaptcha
Related
I wish to create the edit form in Silverstripe 4.2, much like this Stack Overflow's edit function that i'm looking for.
EDITED: I want to be able to have a page that is only available to the registered member of my website that they can post their class listings on the Frontend (not in CMS) as an owner, and need to have a 'edit' click that takes you to an identical form (same ClassListingForm) that lets member owner to edit/update their own class listings that they have posted. I have everything working except the edit and submit functions which I'm stuck on at the moment.
I have a link for editing the specific class listing:
Edit class listing</div>
It does redirected to 404 page not found with this url shown:
"http://.../learners/class-listings/edit/61"
Here's the code below I have so far, the ClassListingForm is working fine, just need to get the EditListingForm and doClassListing functions to work properly, and i may be doing something wrong in these codes? or is there a better way of doing the edit form properly which i'm unable to find anywhere on the search for specific on what i need as there's not much tutorial that covers the EditForm function on the SilverStripe lessons.
<?php
class ClassListings extends DataObject {
private static $table_name = 'ClassListings';
private static $db = [
'CourseTitle' => 'Varchar(255)',
'CourseLocation' => 'Varchar(255)',
];
private static $has_one = [
'ClassListingPage' => ClassListingPage::class,
];
}
<?php
class ClassListingPageController extends PageController {
private static $allowed_actions = [
'ClassListingForm',
'ClassEditForm'
];
public function ClassListingForm() {
$id = (int)$this->urlParams['ID'];
$data = ($id)? $data = ClassListings::get()->byID($id) : false;
$form = Form::create(
$this,
__FUNCTION__,
FieldList::create(
TextField::create('CourseTitle', 'Course title:')
->setAttribute('placeholder', 'NZSL Level 1, NZSL 1A')
->setCustomValidationMessage('Please enter the course title field')
->addExtraClass('requiredField CourseTitle'),
TextField::create('CourseLocation','Region:')
->setAttribute('placeholder', 'Enter region')
->setCustomValidationMessage('Please enter the region field')
->addExtraClass('requiredField'),
HiddenField::create('ID', 'ID')->setValue($ClassListingPageID)
),
FieldList::create(
FormAction::create('handleClassListing')
->setTitle('Post your class listing')
->addExtraClass('btn btn-primary primary')
),
RequiredFields::create(
'CourseTitle',
'CourseLocation'
)
);
$form->loadDataFrom(Member::get()->byID(Member::currentUserID()));
$form->getSecurityToken()->getValue();
if ($form->hasExtension('FormSpamProtectionExtension')) {
$form->enableSpamProtection();
}
$data = $this->getRequest()->getSession()->get("FormData.{$form->getName()}.data");
return $data ? $form->loadDataFrom($data) : $form;
}
public function handleClassListing($data, $form) {
$session = $this->getRequest()->getSession();
$session->set("FormData.{$form->getName()}.data", $data);
$class = ClassListings::create($this->owner);
$class->CourseTitle = $data['CourseTitle'];
$class->CourseLocation = $data['CourseLocation'];
$class->ID = $data['ID'];
$class->ClassListingPageID = $this->ID;
$form->saveInto($class);
$class->write();
$session->clear("FormData.{$form->getName()}.data");
$form->sessionMessage('Your class listing has been posted!','good');
$session = $this->getRequest()->getSession();
return $this->redirect($this->Link());
}
public function ClassEditForm() {
$ClassListingPageID = (int)$this->urlParams['ID'];
$data = ($ClassListingPageID)? $data = ClassListings::get()->byID($ClassListingPageID) : false;
$var = $this->getRequest()->getVar('$data');
if($var){
$form = Form::create(
$this,
__FUNCTION__,
FieldList::create(
TextField::create('CourseTitle', 'Course title:')
->setAttribute('placeholder', 'NZSL Level 1, NZSL 1A')
->setCustomValidationMessage('Please enter the course title field')
->addExtraClass('requiredField CourseTitle'),
TextField::create('CourseLocation','Region:')
->setAttribute('placeholder', 'Enter region')
->setCustomValidationMessage('Please enter the region field')
->addExtraClass('requiredField'),
HiddenField::create('ID', 'ID')->setValue($ClassListingPageID)
),
FieldList::create(
FormAction::create('doClassListing')
->setTitle('Post your class listing')
->addExtraClass('btn btn-primary primary')
),
RequiredFields::create(
'CourseTitle',
'CourseLocation',
)
);
$form->loadDataFrom(ClassListings::get()->filter(['ClassListingPageID' => $var])[0]);
$form->getSecurityToken()->getValue();
if ($form->hasExtension('FormSpamProtectionExtension')) {
$form->enableSpamProtection();
}
$data = $this->getRequest()->getSession()->get("FormData.{$form->getName()}.data");
return $data ? $form->loadDataFrom($data) : $form;
}
return;
}
public function doUpdateClassListing($data, Form $form) {
$session = $this->getRequest()->getSession();
$session->set("FormData.{$form->getName()}.data", $data);
$class = ClassListings::create($this->owner);
$class->CourseTitle = $data['CourseTitle'];
$class->CourseLocation = $data['CourseLocation'];
$class->ID = $data['ID'];
$class->ClassListingPageID = $this->ID;
$form->saveInto($class);
$class->write();
$session->clear("FormData.{$form->getName()}.data");
$form->sessionMessage('Your class listing has been updated!','good');
$session = $this->getRequest()->getSession();
return $this->redirect($this->Link());
}
}
Thought i post this answer to share in case if others have the same issue i had.
Finally got it working and solved the issue now, have replaced whole the codes for both ClassEditForm and doUpdateClassListing methods, and also created another funcation called Edit:
public function Edit(HTTPRequest $request) {
$id = (int)$request->param('ID');
$class = ClassListings::get()->byID($id);
if (!$class || !$class->exists()) {
return ErrorPage::response_for(404);
}
$form = $this->ClassEditForm($class);
$return = $this->customise(array(
'Title' => 'Edit: ' . $class->CourseTitle,
'Form' => $form,
));
return $return = $return->renderWith(array('ClassListingPage_edit', 'Page'));
}
public function ClassEditForm() {
$id = (int)$this->urlParams['ID'];
$class = ClassListings::get()->byID($id);
$fields = new FieldList(
HiddenField::create('ID')->setValue($id),
TextField::create('CourseTitle', 'Course title:')
->setAttribute('placeholder', 'NZSL Level 1, NZSL 1A')
->setCustomValidationMessage('Please enter the course title field')
->addExtraClass('requiredField CourseTitle'),
TextField::create('CourseLocation','Region:')
->setAttribute('placeholder', 'Enter region')
->setCustomValidationMessage('Please enter the region field')
->addExtraClass('requiredField')
);
$actions = new FieldList(
FormAction::create('doUpdateClassListing')
->setTitle('Update your class listing')
->addExtraClass('btn btn-primary primary')
);
$validator = new RequiredFields([
'CourseTitle',
'CourseLocation'
]);
$form = Form::create($this, 'ClassEditForm', $fields, $actions, $validator);
if ($class) $form->loadDataFrom($class);
return $form;
}
public function doUpdateClassListing($data, Form $form) {
if($data['ID']){
$id = $data['ID'];
$class = ClassListings::get()->byID($id);
} else {
$class = ClassListings::create();
}
$form->saveInto($class);
$id = $class->write();
$form->sessionMessage('Your class listing has been updated!','good');
$this->redirect($this->Link() . "edit/".$id);
}
is there a way to pass a URL variable to a form action? I've got it working on a user details form, but when I'm trying to do it with a user file upload it won't work.
As you will see below, I have a form and a save action for saving user details. That works fine.
When I try to pass the URL variable to the User File Upload form, it doesn't work. It says that I'm trying to get a value of a non-object.
// Get Client ID from URL Parameters
public function getUser() {
if( isset($this->urlParams['ID']) && is_numeric($this->urlParams['ID']) ) {
return $user = Member::get()->byID($this->urlParams['ID']);
} else {
return $user = $this->request->postVars();
}
}
// Edit/Save a User's details
public function EditUserDetails() {
//Include JS for updating details
Requirements::javascript('module-memberprofiles/javascript/MemberProfileUpdate.js');
Requirements::set_force_js_to_bottom(true);
$fields = new FieldList(
$leftCol = CompositeField::create(
TextField::create('FirstName', 'First Name')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
TextField::create('Surname', 'Surname')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
CompositeField::create(
TextField::create('Address', ''),
TextField::create('Suburb', ''),
CompositeField::create(
DropdownField::create('State', '', singleton('Member')->dbObject('State')->enumValues())->setFieldHolderTemplate('UserDetails_StatePostCode'),
TextField::create('PostCode', '')->setFieldHolderTemplate('UserDetails_StatePostCode')
)->addExtraClass('row')
)
->addExtraClass('userdetails-address wrap')
->setFieldHolderTemplate('UserDetails_AddressHolder'),
TextField::create('Phone', 'Phone')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
TextField::create('Email', 'Email')
->setFieldHolderTemplate('UserDetails_FieldHolder')
)->setFieldHolderTemplate('UserDetails_CompositeField')
);
$actions = new FieldList(new FormAction('SaveUserDetails', 'Save Profile'));
$validation = new RequiredFields(array('FirstName','Surname','Email'));
$form = new Form ( $this, 'EditUserDetails', $fields, $actions, $validation);
$form->loadDataFrom($this->getUser());
$form->setTemplate('MemberProfilePage_UserDetailsForm');
return $form;
}
public function SaveUserDetails($data, $form) {
$table = Member::get()->byID($this->getUser());
$members = Member::get();
$emailExists = $members->filter(array(
'Email' => $data['Email'],
'ID:not' => $table->ID
));
if( $emailExists->count() > 0 ) {
$form->sessionMessage('Sorry, that email address already exists. Please try again','bad');
return $this->redirectBack();
} else {
$form->sessionMessage('You have successfully updated this user\'s details.','good');
}
$form->saveInto($table);
$table->write();
$this->redirectBack();
return $this;
}
//User file upload function
public function UploadUserFile() {
$fields = FieldList::create(
FileField::create('UserFiles', 'Upload files')
);
$actions = FieldList::create(FormAction::create('SaveUserFile', 'Upload files'));
$form = Form::create($this, __FUNCTION__, $fields, $actions, null);
$form->loadDataFrom($this->getUser());
return $form;
}
//Refresh files function
public function SaveUserFile($data, $form) {
$up = new Upload();
$file = Object::create('File');
$file->setFileName('newname');
$up->loadIntoFile($data['UserFiles'], $file, 'User-Files');
if($up->isError()) {
//handle error here
//var_dump($up->getErrors());
}else {
//file uploaded
//$file->OwnerID = 3;
//$file->write();
//$this->redirectBack();
return $this;
}
}
OK, I managed to figure this one out...
I had to set a form action to direct the upload function to the correct URL. It appears that the ID was being removed from the URL when I clicked submit, so the "getUser" function couldn't see the value.
Here's the working code for the Upload Form function:
public function UploadUserFile() {
$fields = FieldList::create(
FileField::create('UserFiles', 'Upload files'),
HiddenField::create('ID','',$this->getUser()->ID)
);
$actions = FieldList::create(
FormAction::create('SaveUserFile', 'Upload files')
->addExtraClass('button rounded solid')
);
$form = Form::create($this, 'UploadUserFile', $fields, $actions);
$form->setFormAction($this->Link().'UploadUserFile/'.$this->getUser()->ID);
return $form;
}
I want to add some fields by default using Userforms plugin in Silverstripe 3.2
I think i found the function which adds fields when the 'Add Field' button is pressed in Gridfield, but i`m not sure and i don't know how to adda formfield type (Date input) by calling a simple function.
Here is the full function:
public function getFieldEditorGrid() {
Requirements::javascript(USERFORMS_DIR . '/javascript/FieldEditor.js');
$fields = $this->owner->Fields();
$this->createInitialFormStep(true);
$editableColumns = new GridFieldEditableColumns();
$fieldClasses = singleton('EditableFormField')->getEditableFieldClasses();
$editableColumns->setDisplayFields(array(
'ClassName' => function($record, $column, $grid) use ($fieldClasses) {
if($record instanceof EditableFormField) {
return $record->getInlineClassnameField($column, $fieldClasses);
}
},
'Title' => function($record, $column, $grid) {
if($record instanceof EditableFormField) {
return $record->getInlineTitleField($column);
}
}
));
$config = GridFieldConfig::create()
->addComponents(
$editableColumns,
new GridFieldButtonRow(),
GridFieldAddClassesButton::create('EditableTextField')
->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD', 'Add Field'))
->setButtonClass('ss-ui-action-constructive'),
GridFieldAddClassesButton::create('EditableFormStep')
->setButtonName(_t('UserFormFieldEditorExtension.ADD_PAGE_BREAK', 'Add Page Break')),
GridFieldAddClassesButton::create(array('EditableFieldGroup', 'EditableFieldGroupEnd'))
->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD_GROUP', 'Add Field Group')),
new GridFieldEditButton(),
new GridFieldDeleteAction(),
new GridFieldToolbarHeader(),
new GridFieldOrderableRows('Sort'),
new GridFieldDetailForm()
);
$fieldEditor = GridField::create(
'Fields',
_t('UserDefinedForm.FIELDS', 'Fields'),
$fields,
$config
)->addExtraClass('uf-field-editor');
return $fieldEditor;
}
We can call onAfterWrite to set default fields after the page is saved for the first time.
class CustomFormPage extends UserDefinedForm {
public function onAfterWrite() {
if (!$this->Fields() || !$this->Fields()->exists()) {
$nameField = new EditableTextField();
$nameField->Name = 'Name';
$nameField->Title = 'Name';
$nameField->ParentID = $this->ID;
$nameField->Required = true;
$nameField->CustomErrorMessage = 'Please enter your name.';
$nameField->write();
$dateField = new EditableDateField();
$dateField->Name = 'Date';
$dateField->Title = 'Date';
$dateField->ParentID = $this->ID;
$dateField->Required = true;
$dateField->CustomErrorMessage = 'Please enter this date.';
$dateField->write();
}
parent::onAfterWrite();
}
}
I'm currently working on a project using the Phalcon Framework that has pages with complex forms and a lot of inputs, to break it down nicely I'm dividing the forms into a step-by-step process.
How would one validate the form on each step before going to the next step and then save the whole form on the final step?
I can't seem to find anything documented about this sort of process as it likes to validate the form in it's entirety if I use the form builder.
Simple, just create a custom methods in your form class to validate any step, and the posted data from some step save into message class and store it into session by "stepX", when posted data is not valid just set defaults from post. When valid save it into session as i describe above.
For example how i mean "controller"
<?php
class MyController extends BaseController {
public function processStep1Action(){
$form = new MyForm();
if($this->request->isPost()){//im using my custom request class
if(!$form->isValid($this->request->getPost()){
//error messages goes here
$form->setDefaultsFromRequest($this->request); // it will set the filled data
}
else {
$messageClass = new MyMessageContainer();
$messageClass->setData($this->request);//inside parse requested data into message class, or parse it as $messageClass->name = $this->request->getPost('name');
$this->session->save('step1',$messageClass); //maybe it would be want to serialize it
//then redirect to the step 2 or x
}
}
}
}
So in the next step you can access data from sessions $this->session->get('step1'); so you can in final step load all posted data and store it into DB.
I hope this helps! :)
here is my form maybe it can be helpful for you.
<?php
namespace Manager\Library\Forms\User;
use Phalcon\Forms\Form,
Phalcon\Forms\Element\Email,
Phalcon\Forms\Element\Select,
Phalcon\Forms\Element\Password,
Phalcon\Forms\Element\Check,
Phalcon\Validation\Validator\Confirmation,
Phalcon\Validation\Validator\StringLength,
Phalcon\Forms\Element\Submit,
Phalcon\Validation\Validator\PresenceOf,
Model\Group;
class AddUser extends Form {
public function initialize()
{
$email = new Email('email');
$email->addValidators(array(
new \Phalcon\Validation\Validator\Email(array(
'message' => 'Nezadali jste email nebo má nesprávny tvar(email#domena.tld).'
))
));
$this->add($email);
$this->initGroupElement();
$password = new Password('password');
$password
->addValidator(new StringLength(array('min' => 6,'messageMinimum' => 'Nezadali jste heslo nebo je příliš krátke, minimální počet znaků je 6.')))
->addValidator(new Confirmation(array('with' => 'password-again',"message" => "Zadané hesla se neshodují.")));
$this->add($password);
$repeatPassword = new Password('password-again');
$this->add($repeatPassword);
$this->initializeProfileElements();
$active = new Check('active',array('value' => 1));
$this->add($active);
$this->add( new Submit('save') );
\Phalcon\Tag::setDefault('password', '');
\Phalcon\Tag::setDefault('password-again', '');
}
public function initializeEdit(){
$email = new Email('email');
$email->addValidators(array(
new \Phalcon\Validation\Validator\Email(array(
'message' => 'Nezadali jste email nebo má nesprávny tvar(email#domena.tld).'
))
));
$this->add($email);
$this->initGroupElement();
$password = new Password('password');
$this->add($password);
$repeatPassword = new Password('password-again');
$this->add($repeatPassword);
$this->initializeProfileElements();
$active = new Check('active',array('value' => 1));
$this->add($active);
$this->add( new Submit('save') );
\Phalcon\Tag::setDefault('password', '');
\Phalcon\Tag::setDefault('password-again', '');
}
protected function initGroupElement(){
$auth = \Core\Auth::getIdentity();
$groups = new Group();
// $groups->addColumns(array('id','name'));
//set global condition about Super Admin
$groups->addFilter('id', 1,'<>');
if($auth){
//set restrictions for main groups
if((int)$auth->group_id === 1){ //super admingroup
//no filter
}
else if((int)$auth->group_id === 2){ //admin group
$groups->addFilter('id', 1,'>');
}
else if((int)$auth->group_id === 6){//Provozovatel group
$groups->addFilter('id',array(3,6,7));
$groups->addFilter('public', 1,'=',true);
}
else { // other groups
$groups->addFilter('public', 1);
}
}
$groups = $groups->findFiltered();
$groupElement = new Select('group');
foreach($groups as $group){
$groupElement->addOption(array($group->id => $group->name));
}
$this->add($groupElement);
}
protected function initializeProfileElements(){
$forename = new \Phalcon\Forms\Element\Text('forename');
$this->add($forename);
$surname = new \Phalcon\Forms\Element\Text('surname');
$this->add($surname);
$street = new \Phalcon\Forms\Element\Text('street');
$this->add($street);
$postal = new \Phalcon\Forms\Element\Text('postal');
$this->add($postal);
$city = new \Phalcon\Forms\Element\Text('city');
$this->add($city);
$ic = new \Phalcon\Forms\Element\Text('ic');
$this->add($ic);
$dic = new \Phalcon\Forms\Element\Text('dic');
$this->add($dic);
}
public function setDefault($fieldName,$value){
\Phalcon\Tag::setDefault($fieldName, $value);
}
public function setDefaults($object){
if($object instanceof \Model\User){
$this->setDefaultsFromObject($object);
}
else if($object instanceof \Phalcon\Http\Request){
$this->setDefaultsFromRequest($object);
}
}
protected function setDefaultsFromObject(\Model\User $user){
$profile = $user->getRelated('\Model\Profile');
\Phalcon\Tag::setDefaults(array(
'email' => $user->email,
'group' => $user->group_id,
'active' => $user->active,
'forename' => $profile->forename,
'surname' => $profile->surname,
'street' => $profile->street,
'city' => $profile->city,
'postal' => $profile->postal,
'ic' => $profile->IC,
'dic' => $profile->DIC
));
}
protected function setDefaultsFromRequest(\Phalcon\Http\Request $request){
\Phalcon\Tag::setDefaults(array(
'email' => $request->getPost('email'),
'group' => $request->getPost('group'),
'active' => $request->getPost('active')
));
\Phalcon\Tag::setDefaults(array(
'forename' => $request->getPost('forename'),
'surname' => $request->getPost('surname'),
'street' => $request->getPost('street'),
'city' => $request->getPost('city'),
'postal' => $request->getPost('postal'),
'ic' => $request->getPost('ic'),
'dic' => $request->getPost('dic')
));
}
}
In addition to Kamil's answer, another option to consider is to use Javascript on the front-end to handle your multi-step form. This will add some complexity as you will need to have the javascript to handle the form steps and do preliminary validation, but it only requires a single submit where you can validate content within a single method.
i make a controller in zf2 for save data in mongodb but it not save any record in event table,how i save data?here is my code:
public function createAction()
{
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
//echo $calendar_id;
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$calendar_id);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
//$form = new CalendarForm();
//$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}
I set code and save data using mongoodm,here is my code:
public function createAction()
{
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($calendar_id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$post['calendar_id']);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
$form = new EventForm();
$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}