I'm just learning zf2, and the basic tutorial from official document is great. Now, I would like to challenge myself to create multi page form in one page, something like that http://demo.stepblogging.com/multi-step-form/
So, currently I have two forms called "Contact Form" and "Album Form".
The idea is i want to split to 2 forms. The problem is when i finish all the fields on the first form, i'm not sure how to go to next form. I'm not sure i can do the logic at Controller, what i know most of the online tutorials are using javascript to handle the next and back button. Or maybe have better idea?
So this is my Controller page.
public function multipleAction(){
$formOne = new ContactForm();
$formTwo = new AlbumForm();
$formOne->get('next')->setValue('Next');
$request = $this->getRequest();
if($request->isPost()){
$aa = new ContactFilter();
$formOne->setInputFilter($aa);
$formOne->setData($request->getPost());
if ($formOne->isValid()) {
//save session
//maybe display second form or any other solution
}
}
my multiple.phtml page contains 2 forms
<ul id="signup-step">
<li id="contact" class="active">Contact</li>
<li id="album">Album</li>
</ul>
<?php
$form_one = $this->form_one;
//$form_one->setAttribute('action', $this->url('album', array('action' => 'multiple')));
$form_one->prepare();
//echo $_SESSION['name'];
echo $this->form()->openTag($form_one); ?>
<div id="contact-field">
<legend>Contact</legend>
<?php
echo $this->formHidden($form_one->get('id'));
echo $this->formLabel($form_one->get('name')).'<br>';
echo $this->formInput($form_one->get('name'))."<br>";
echo $this->formElementErrors($form_one->get('name'));
echo $this->formLabel($form_one->get('artist')).'<br>';
echo $this->formInput($form_one->get('artist'))."<br>";
echo $this->formElementErrors($form_one->get('artist'));
echo $this->formLabel($form_one->get('address')).'<br>';
echo $this->formInput($form_one->get('address'))."<br><br>";
echo $this->formElementErrors($form_one->get('address'));
echo $this->formSubmit($form_one->get('next'));
echo $this->form()->closeTag($form_one);
?>
<?php
$form_two = $this->form_two;
$form_two->prepare();
echo $this->form()->openTag($form_two); ?>
<div id="album-field" >
<legend>Album</legend>
<?php
echo $this->formLabel($form_two->get('title')).'<br>';
echo $this->formInput($form_two->get('title'))."<br>";
echo $this->formElementErrors($form_two->get('title'));
echo $this->formLabel($form_two->get('artist'))."<br>";
echo $this->formInput($form_two->get('artist'))."<br>";
echo $this->formElementErrors($form_two->get('artist'));
echo $this->form()->closeTag($form_two);
?>
The code below is very crude and is only for example purposes (made this in 10 mins and looks like it)
So basically all we are doing is the following -
Creating a session
Checking if there is any data in the session for that particular form, if there is one then use setData() to set the data on the form
If the form posts data, then validate & filter it and then save that data to the session
The "Submit" button value in the form is used to determine the navigation path i.e. previous or next page.
The final page will save data from the session to the DB (or whatever you want to do with it) and of course destroy the session as well.
Controller
/** #var Zend\Session\Container Session Object */
private $session;
public function __construct()
{
// Put a meaningful name in the constructor
$this->session = new Container();
}
public function page1Action()
{
// This should really be injected...
$form = new Form\Form1();
// Proper validation & filtering needs to be done for every form (this is example only)
$form->setInputFilter(new InputFilter());
// Populates form data from the session if it already exists
if (isset($this->session->form1Inputs)) {
$form->setData($this->session->form1Inputs);
}
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$formData = $form->getData();
// Saves the new data to the session
$this->session->form1Inputs = $formData;
// Redirects to next page
if ($formData['Next'] === 'Next') {
$this->redirect()->toRoute('application', ['controller' => 'Index', 'action' => 'page2']);
}
}
}
return new ViewModel(['form' => $form]);
}
public function page2Action()
{
// This should really be injected...
$form = new Form\Form2();
// Proper validation & filtering needs to be done for every form (this is example only)
$form->setInputFilter(new InputFilter());
// Populates form data from the session if it already exists
if (isset($this->session->form2Inputs)) {
$form->setData($this->session->form2Inputs);
}
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$formData = $form->getData();
// Saves the new data to the session
$this->session->form2Inputs = $formData;
// Redirects to next or previous page
if ($formData['Next'] === 'Next') {
$this->redirect()->toRoute('application', ['controller' => 'Index', 'action' => 'page3']);
} elseif ($formData['Previous'] === 'Previous') {
$this->redirect()->toRoute('application', ['controller' => 'Index', 'action' => 'page1']);
}
}
}
return new ViewModel(['form' => $form]);
}
public function page3Action()
{
// This should really be injected...
$form = new Form\Form3();
// Proper validation & filtering needs to be done for every form (this is example only)
$form->setInputFilter(new InputFilter());
// Populates form data from the session if it already exists
if (isset($this->session->form2Inputs)) {
$form->setData($this->session->form2Inputs);
}
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$formData = $form->getData();
// Saves the new data to the session
$this->session->form3Inputs = $formData;
// Finalise or redirect to previous page
if ($formData['Finalise'] === 'Finalise') {
// Save all data to DB from session & destroy
} elseif ($formData['Previous'] === 'Previous') {
$this->redirect()->toRoute('application', ['controller' => 'Index', 'action' => 'page2']);
}
}
}
return new ViewModel(['form' => $form]);
}
Form 1
public function __construct($name = null)
{
parent::__construct($name);
$this->add(['name' => 'Form1Text1', 'type' => 'Text', 'options' => ['label' => 'Form 1 Text 1 : ']]);
$this->add(['name' => 'Form1Text2', 'type' => 'Text', 'options' => ['label' => 'Form 1 Text 2 : ']]);
$this->add(['name' => 'Next', 'type' => 'Submit', 'attributes' => ['value' => 'Next']]);
}
Form 2
public function __construct($name = null)
{
parent::__construct($name);
$this->add(['name' => 'Form2Text1', 'type' => 'Text', 'options' => ['label' => 'Form 2 Text 1 : ']]);
$this->add(['name' => 'Form2Text2', 'type' => 'Text', 'options' => ['label' => 'Form 2 Text 2 : ']]);
$this->add(['name' => 'Next', 'type' => 'Submit', 'attributes' => ['value' => 'Next']]);
$this->add(['name' => 'Previous', 'type' => 'Submit', 'attributes' => ['value' => 'Previous']]);
}
Form 3
public function __construct($name = null)
{
parent::__construct($name);
$this->add(['name' => 'Form3Text1', 'type' => 'Text', 'options' => ['label' => 'Form 3 Text 1 : ']]);
$this->add(['name' => 'Form3Text2', 'type' => 'Text', 'options' => ['label' => 'Form 3 Text 2 : ']]);
$this->add(['name' => 'Previous', 'type' => 'Submit', 'attributes' => ['value' => 'Previous']]);
$this->add(['name' => 'Finalise', 'type' => 'Submit', 'attributes' => ['value' => 'Finalise']]);
}
i don't think i have understand exactly what you want,
but if you mean multiple steps with different form, so you have just to put the
previous step result in session,
your question is fuzzy. your given link is also done by jquery!... As far as I understand you want this demo page behavior without using js/jquery.
1. break this one form into three form. For easiness add a hidden field step
2. make next and back button input type submit
3. after submit in your action check submitted value and determine what you want ...[show next form or whatever]
Related
I'm developing an application with Cakephp and I can't find my answer in existing topics...
I have a main menu with several action (Edit/Delete/Add) which is manage sockets. When I edit a socket and I submit my update, my socket is updated correctly BUT my redirection on the main menu doesn't work. The URL stay the same.
For example, I edit socket with id = 2. The application go to '/my/app/sockets/edit/2'. After update and submit, the application should redirect to '/my/app/sockets/index' but it doesn't work.
Below, you can see my code.
SocketsController.php :
public function index($searchCloset = null) {
$this->Paginator->settings = $this->paginate;
if($searchCloset != null) {
$sockets = $this->paginate('Socket', array(
'Closet.name LIKE' => $searchCloset
));
}
else{
$sockets = $this->paginate('Socket');
$searchCloset = '' ;
}
$this->set('sockets',$sockets);
$this->set('closets',$this->Socket->Closet->find('all'));
$this->set('searchCloset',$searchCloset);
}
public function edit($id = null){
// Bad socket management
if (!$id) {
throw new NotFoundException(__('Invalid socket'));
}
$socket = $this->Socket->findByid_socket($id);
if (!$socket) {
throw new NotFoundException(__('Invalid socket'));
}
// if there's a submit
if ($this->request->is(array('post'))) {
$this->Socket->id = $id;
if ($this->Socket->save($this->request->data)) {
// update 'lastchange' column
if($this->updateSocketStatus($this->Socket->id)){
$this->Session->setFlash(__('Your socket has been updated.'));
}
else {
$this->Session->setFlash(__('Unable to create history.'));
}
}
else {
$this->Session->setFlash(__('Unable to update your socket.'));
}
return $this->redirect(array('controller' => 'sockets','action' => 'index'));
}
// send all informations about the socket to the view
$this->set('socket',$socket);
// send closets list to the view (select menu)
$this->set('closets',$this->Socket->Closet->find('list',array(
'fields' => array('Closet.id_closet','Closet.name')
)));
}
edit.ctp :
<h2>Edit socket</h2>
<div><?php
echo $this->Form->create('Socket');
echo $this->Form->input('Socket.name', array(
'label' => 'Socket name :',
'default' => $socket['Socket']['name']
));
echo $this->Form->input('Socket.location', array(
'label' => 'Location :',
'default' => $socket['Socket']['location']
));
echo $this->Form->input('Socket.comment', array(
'label' => 'Comment :',
'default' => $socket['Socket']['comment']
));
echo $this->Form->input('Socket.closet_id',array(
'type' => 'select',
'label' => 'Closet :',
'options' => $closets,
'default' => $socket['Closet']['id_closet']
));
echo $this->Form->end('Save socket');
echo $this->Form->postButton(
'Back',
array('controller' => 'sockets','action' => 'index'),
array(
'id' => 'back_button',
'class' => 'ui-btn ui-btn-inline ui-icon-back ui-btn-icon-left'
)
);
?></div>
I've already search and it could be a cache problem.
Thanks in advance.
Can you force with
$this->redirect($this->referer());
Please, try and comment
Your request checking if-statement is omitted, because is() method accepts param of string type according to documentation.
So you should change line:
if ($this->request->is(array('post'))) { ... }
into:
if ($this->request->is('post')) { ... }
I am trying to set up an edit form for an entity (Place) in my app. For this purpose I have written the form (PlaceForm), fieldset (PlaceFieldset), .phtml pages and functions in the controller. Since I am new in zf2, I have concentrated on the tutorlias on their homepage. I have seen that from validation is provided by the framework but in my case it is not necessary. None of the fields added in the fieldset have not the required attribute, however when I submit the form under all empty fields I get the message "Value is required and can't be empty" although it is actually not required. I do not want to create a wall of code in this question, so I will start with the function from the controller. If there is someone who would like to help me with this issue, just let me know and I will update any other part of the code (form, fieldset etc.) Thx in advance.
...
public function editPlaceAction() {
$id = $this->params()->fromRoute('id');
$uiServiceProvider = $this->getServiceLocator()->get('FamilyTree\Service\UiServiceProvider');
$placeArray = $uiServiceProvider->fetchSinglePlaceById($id);
$place = new Places($placeArray);
$form = new PlaceForm();
$form->bind($place);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
var_dump($place);
}
}
$view = new ViewModel(array(
'form' => $form,
'title'=>"Edit place"
));
$view->setTemplate("family-tree/family-tree-maintenance/editPlace");
return $view;
}
...
and here you can see how my Fieldset looks like
<?php
namespace Places\Form;
use Zend\Form\Fieldset;
class PlaceFieldset extends Fieldset {
public function __construct() {
parent::__construct('place');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'name',
'type' => 'Text',
'options' => array(
'label' => 'Name',
),
));
$this->add(array(
'name' => 'admUnit1',
'type' => 'Text',
'options' => array(
'label' => 'AdmUnit1',
),
));
}
}
I am new to Symfony2. I have created a form which has 3 sets of radio buttons and a submit button. To display the form, I have used a FormType. Now, I have to apply a condition that the user can only select only a maximum of any 2 sets of radio buttons(and a minimum of 0 sets of radio buttons) and not 3 sets of radio buttons. If the user selects 3 sets of radio buttons and clicks on submit then I want to throw an error message to the user saying that "You can select only 2".
This is the FormType "SubscriptionsType.php"
<?php
namespace InstituteEvents\StudentBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class SubscriptionsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('event1', 'choice', array('choices' => array('1' => 'Tourism', '2' => 'Food party', '3' => 'South korean food', '4' => 'Cooking', '5' => 'None of the above'), 'data' => '5', 'expanded' => true, 'multiple' => false))
->add('event2', 'choice', array('choices' => array('6' => 'Cricket', '7' => 'Football', '8' => 'Hockey', '9' => 'Baseball', '10' => 'Polo', '5' => 'None of the above'), 'data' => '5', 'expanded' => true, 'multiple' => false))
->add('event3', 'choice', array('choices' => array('11' => 'Game 1', '12' => 'Game 2', '13' => 'Game 3', '14' => 'Game 4', '15' => 'Game 5', '5' => 'None of the above'), 'data' => '5', 'expanded' => true, 'multiple' => false))
->add('register', 'submit');
}
public function getName()
{
return 'subscriptions';
}
}
This is the controller "DefaultController"
<?php
namespace InstituteProjectEvents\StudentBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use InstituteProjectEvents\StudentBundle\Entity\Subscriptions;
use InstituteProjectEvents\StudentBundle\Form\Type\SubscriptionsType;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller {
public function eventsoneAction(Request $request) {
$subscriptions = new Subscriptions();
//Get the logged in users id
$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();
//Check if events already selected by user
$repository = $this->getDoctrine()->getManager()
->getRepository('InstituteProjectEventsStudentBundle:Subscriptions');
$query = $repository->findOneBy(array('id' => $userId));
if(($query == NULL)) {
$subscriptions->setEvent1(5);
$subscriptions->setEvent2(5);
$subscriptions->setEvent3(5);
$subscriptions->setStudents($userId);
$form = $this->createForm(new SubscriptionsType(), $subscriptions);
$form->handleRequest($request);
}
else {
$subscriptions->setEvent1($query->getEvent1());
$subscriptions->setEvent2($query->getEvent2());
$subscriptions->setEvent3($query->getEvent3());
$subscriptions->setStudents($userId);
$form = $this->createForm(new SubscriptionsType(), $subscriptions);
$form->handleRequest($request);
}
if ($form->isValid()) {
//Save to the Database
$em = $this->getDoctrine()->getManager();
$em->persist($subscriptions);
$em->flush();
return $this->redirect($this->generateUrl('InstituteProject_events_student_eventsregistered'));
}
if($current_date > date_format($date,"Y/m/d h:i:s a")) {
return $this->render('InstituteProjectEventsStudentBundle:Default:registrationsclosed.html.twig');
}
else {
$form = $this->createForm(new SubscriptionsType(), $subscriptions);
return $this->render('InstituteProjectEventsStudentBundle:Default:eventsday1.html.twig', array('form' => $form ->createView()));
}
}
/**
* This action displays the Confirmation page on success.
*/
public function eventsregisteredAction() {
return $this->render('InstituteProjectEventsStudentBundle:Default:eventsregistered.html.twig');
}
}
What is the validation that needs to be written in "DefaultController.php" to apply the rule of only selection of maximum of 2 sets of radio buttons and a minimum of 0?
what about applying Callback constraint to whole form fields?
...
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver
->setDefaults(array(
...
'constraints' => array(
new Callback(
array('callback' => array($this, 'validateForm'))
)
)
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
if (CONDITION) {
// build and add violation
}
}
Alternatively you can check Request object..
In order to do what you want to do you need to set
'required' => false
to event1, event2, and event3 since required is set to true by default. Then you'll need to add a javascript (or jquery) listener for the form submit and have that insert the error message if all three fields are selected. However, you'll run into the problem of not being able to unselect a radio button since once you select a radio button you can't unselect it, so once you have selected something for all three you'll never be able to submit the form without refreshing the page. So you may want to do some workflow changes if you take this route.
Alternatively, you can just do a manual check in your controller and then add the error manually by
$form->get('event3')->addError('you can only select 2');
but you'll need to 'clear' your subscriptions otherwise it will re-render the form with the previous selections already filled and you'll enter an infinite loop.
I got the answer, by replacing the following code in the above "DefaultController.php" :-
if ($form->isValid()) {
//Get the submitted form's data
$subscriptions2 = $form->getData();
//To check if the user has selected more than 2 events or not
if(($subscriptions2->getEvent1() != 5) && ($subscriptions2->getEvent2() != 5) && ($subscriptions2->getEvent3() != 5)) {
echo 'You can select only a maximum of 2 events';
echo '<br>';
return $this->render('InstituteProjectEventsStudentBundle:Default:eventsday1.html.twig', array('form' => $form ->createView()));
}
Here, it is to be noted that I have given all the "None of the above" radio buttons as value 5 in "SubscriptionsType.php" and 5 as the event id to all the "None of the above" in the table of "Events" in the database.
I am having a problem in my symfony 2 project regarding the use of form (forms without classes). The idea is to develop a sequence of forms (each one in an independent page). Similar to multistep form or wizard but exactly not the same. In each form, partial sent results are saved and a new form is called.
Currently I have a controller with a form like this:
public function form1Action(Request $request, $parameter){
//Get relevant data using the $parameter...
$defaultData = array('message' => 'Type your message here');
$formBuilder = $this->createFormBuilder($defaultData);
$formBuilder->add('sendreport', 'choice', array(
'choices' => array('yes' => 'Yes', 'no' => 'No'),
'expanded' => true,
'label' => 'You will receive a full report from administrator',
'multiple' => false,
));
$formBuilder->add('start', 'submit', array('label' => 'form.labels.start'));
$form = $formBuilder->getForm();
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isSubmitted() && $form->isValid()){
$data = $form->getData();
return $this->redirect($this->generateUrl('task_form2', array('data' => $data)));
}
return $this->render('MyBundle:Default:showform1.html.twig', array('ourform' => $form->createView()));
}
Then, the redirected page contains a new form with similar structure to the previous one:
public function form2Action(Request $request, $data){
$datasource = $data;
$defaultData = array('message' => 'Type your message here');
$formBuilder = $this->createFormBuilder($defaultData)
->add('name', 'text')
->add('email', 'text')
->add('message', 'textarea')
->add('send', 'submit');
$form = $formBuilder->getForm();
$form->handleRequest($request);
//WHY IS NOT SUBMMITED???
if ($request->getMethod() == 'POST') {
if ($form->isSubmitted() /*&& $form2->isValid()*/) {
$data2 = $form->getData();
$data = //$data = $data2 array + $datasource array...
return $this->redirect($this->generateUrl('task_form3'), array('data' => $data));
}
}
return $this->render('MyBundle:Default:showform2.html.twig', array('ourform' => $form->createView()));
}
But here is the problem, the second form called in 'task_form2' path is not submitted!¿?. When you press the send button nothing happens!.
Any idea?
What is the best way to do this? (I think it is simpler and I would not like to use multistep bundle or something like that).
Thank you in advance.
I have a form that requires the user to enter some information. If they fail to complete the required fields they are re-presented with the form; the top of the page notifying them what fields are required and I've enabled sticky forms (set_value()) so their input is not lost.
I'm using flashdata to display messages to the user (i.e., if what they've entered already exists in the database).
My form is in the index method of my controller.
When submit is clicked from my view it calls the add() method in my controller.
The add() method performs the validation and depending on the results either submits to the database or kicks back out to the user to get more data.
I have several issues with the way that i've done this.
1. If validation fails I'm using $this->index() to get back to my form and display the validation errors. If I try using redirect, I lose my validation errors and my $_POST[] data so my sticky forms end up blank.
2. Using $this->index() appends the 'add' to the end of my url
3. Using $this->index() causes issues with the flashdata. Random results.
Any ideas?
<?php
class Restaurant extends Controller {
function Restaurant() {
parent::Controller();
}
function index() {
// Load libraries and models
$this->load->model('/restaurant/mRestaurantTypes');
$this->load->model('/restaurant/mRestaurant');
$this->load->model('/utilities/mUtilities');
// Get states
$stateSelect = array();
$getStates = $this->mUtilities->getStates();
if($getStates->num_rows() > 0) {
foreach($getStates->result() as $row) {
$stateSelect[$row->abbr] = $row->name;
}
}
// Get restaurant types
$restaurantTypes = array();
$getRestaurantTypes = $this->mRestaurantTypes->getRestaurantTypes();
if($getRestaurantTypes->num_rows() > 0) {
foreach($getRestaurantTypes->result() as $row) {
$restaurantTypes[$row->restaurant_types_id] = $row->type;
}
}
// Create form elements
$data['name'] = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name'),
'maxlength' => '200',
'size' => '50'
);
$data['address'] = array(
'name' => 'address',
'id' => 'address',
'value' => set_value('address'),
'maxlength' => '200',
'size' => '50'
);
$data['city'] = array(
'name' => 'city',
'id' => 'city',
'value' => set_value('city'),
'maxlength' => '50',
'size' => '25'
);
$data['state'] = $stateSelect;
$data['zip'] = array(
'name' => 'zip',
'id' => 'zip',
'value' => set_value('zip'),
'maxlength' => '10',
'size' => '10'
);
$data['phone'] = array(
'name' => 'phone',
'id' => 'phone',
'value' => set_value('phone'),
'maxlength' => '15',
'size' => '15'
);
$data['url'] = array(
'name' => 'url',
'id' => 'url',
'value' => set_value('url'),
'maxlength' => '255',
'size' => '50'
);
$data['type'] = $restaurantTypes;
$data['tags'] = array(
'name' => 'tags',
'id' => 'tags',
'value' => set_value('tags'),
'maxlength' => '255',
'size' => '50'
);
$data['active'] = array(
'name' => 'active',
'id' => 'active',
'value' => 'Y',
'maxlength' => '1',
'size' => '2'
);
// Set page variables
$data_h['title'] = "Add new restaurant";
// Load views
$this->load->view('/template/header', $data_h);
$this->load->view('/restaurant/index', $data);
$this->load->view('/template/footer');
}
/**
* Add the the new restaurant to the database.
*/
function add() {
// Load libraries and models
$this->load->library('form_validation');
$this->load->model('/restaurant/mRestaurant');
// Define validation rules
$this->form_validation->set_rules('name', 'Name', 'trim|required|max_length[255]|xss_clean');
$this->form_validation->set_rules('address', 'Address', 'trim|required|max_length[100]|xss_clean');
$this->form_validation->set_rules('city', 'City', 'trim|required|max_length[128]|xss_clean');
//$this->form_validation->set_rules('state', 'State', 'trim|required');
$this->form_validation->set_rules('zip', 'Zip', 'trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required|max_length[10]|xss_clean');
$this->form_validation->set_rules('url', 'URL', 'trim|required|max_length[255]|xss_clean');
$this->form_validation->set_rules('tags', 'Tags', 'trim|xss_clean');
// Form validation
if ($this->form_validation->run() == FALSE) {
// On failure
$this->index();
} else {
// On success, prepare the data
$data = array(
'name' => $_POST['name'],
'address' => $_POST['address'],
'city' => $_POST['city'],
'state' => $_POST['state'],
'zip' => $_POST['zip'],
'phone' => $_POST['phone'],
'url' => $_POST['url'],
'type' => $_POST['type'],
'tags' => $_POST['tags'],
'active' => $_POST['active'],
);
// Check if the restaurant already exists
$check = $this->mRestaurant->getRestaurant($data['name'], $data['zip']);
// If no records were returned add the new restaurant
if($check->num_rows() == 0) {
$query = $this->mRestaurant->addRestaurant($data);
if ($query) {
// On success
$this->session->set_flashdata('status', '<div class="success">Added New Restaurant!</div>');
} else {
// On failure
$this->session->set_flashdata('status', '<div class="error">Could not add a new restaurant.</div>');
}
redirect('restaurant/confirm', 'refresh');
} else {
// Notify the user that the restaurant already exists in the database
$this->session->set_flashdata('status', '<div class="notice">This restaurant already exists in the database.</div>');
redirect('restaurant/index');
}
}
}
function confirm() {
$data['title'] = "Confirm";
$this->load->view('/template/header');
$this->load->view('/restaurant/confirm', $data);
$this->load->view('/template/footer');
}
}
?>
I will try to help with the logic in the controller that I always use:
function index()
{
//set some default variables
$data['error_message'] = '';
//if this is to edit existing value, load it here
// from database and assign to $data
//...
//set form validation rules
$validation = array();
$validation['field_name'] = array(
'field' => 'field_name',
'label' => 'Field label',
'rules' => 'trim|required'
);
//more rules here
//...
$this->load->library('form_validation');
$this->form_validation->set_rules($validation);
//run validation
if ($this->form_validation->run() == FALSE)
{
$data['error_message'] .= validation_errors();
}
else
{
//do insert/update
//
//it's better to do redirection after receiving post request
//you can use flashdata for success message
if ( $success )
{
$this->session_set_flashdata('success_message', MESSAGE_HERE);
}
redirect(RESULT_PAGE);
}
//reaching this block can have 2 meaning, direct page access, or not have valid form validation
//assign required variables, such as form dropdown option, etc
//...
//load view
$this->load->view(VIEW_FILE, $data);
}
View file:
...
<?php if ( $error_message ): ?>
<?php echo $error_message; ?>
<?php endif; ?>
<?php echo form_open(current_url, array('id' => 'some_form_id')); ?>
<!-- form field here -->
<label for="field_name">Field label</label>
<input name="field_name" value="<?php echo set_value('field_name', $DEFAULT_FIELD_NAME_IF_NEEDED); ?>" />
<!-- more form field here -->
<?php echo form_close(); ?>
...
I hope this will help you.
For the $DEFAULT_FIELD_NAME_IF_NEEDED in the view file, I use this to pass the default value if this form page is to edit existing data from database. You can load the data in the controller, then pass it to view file and display it in the form field.
-------controller-------
$data['post'] = $_POST;
$this->load->view('view/view', $data);
then in your view
<input type="text" value="><?=$post['username'];?>" name="username">
I had a similar problem and I ended up doing:
My form is to create new user but you should get the idea.
if($this->form_validation->run() == FALSE)
{
$this->data['title'] = "Add User";
$this->load->vars($this->data);
$this->load->view('head');
$this->load->view('header');
$this->load->view('admin/sidebar');
$this->load->view('admin/add_user');
$this->load->view('footer');
}
So effectively instead of calling new function I was showing new view from the same function.
Not the nicest solution but it works.
Also you might want to use something like this to check if the restaurant already exists:
function _check_username($str)
{
$this->db->where('username', $str);
$query = $this->db->get('sm_users');
if($query->num_rows() == 0)
{
return TRUE;
}
else
{
$this->form_validation->set_message('_check_username', "User '$str' already exists!");
return FALSE;
}
}
And use callback validation function:
$this->form_validation->set_rules('userName','User Name','trim|required|min_length[3]|callback__check_username');
You could try having the form post to index, and in the index method, do validation if the form has been submitted. Then either render the index view (if there are errors) or add the restaurant and render the confirm view.