I'm using Zend_Form for an application form using this code:
class Form_ApplicationForm extends Zend_Form
{
public function init()
{
$this->setAction('/application/new')
->setMethod('post')
->setAttrib('id','application');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Your Name')
->setRequired(TRUE)
->addValidator('alpha', FALSE, array('allowWhiteSpace' => true));
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email Address')
->setRequired(TRUE)
->addValidator('EmailAddress');
$this->addElements(array($name,$email));
}
}
I'm adding a flash file uploader (swfupload) to this form which needs a HTML snippet to be in place to work, the snippet looks like this:
<div id="swfupload-control">
<p>Upload upto 5 image files(jpg, png, gif), each having maximum size of 1MB(Use Ctrl/Shift to select multiple files)</p>
<input type="button" id="button" />
<p id="queuestatus" ></p>
<ol id="log"></ol>
</div>
What is the best way of inserting this so that it sits somewhere within the <form> which i'm inserting within my controller like this:
public function newAction()
{
$form = new Form_ApplicationForm();
if($this->_request->isPost()){
$data = $_POST;
if($form->isValid($data)){
/// handle data here
}else{
$form->populate($data);
}
}
$this->view->form = $form;
}
Is there a way of adding a placeholder or similar within Zend_Form, or should this be done using a decorator or something like that?
Thanks.
You'd have to write your own Element for this, e.g. My_Form_Element_SwfUpload along with a renderer. See these tutorials:
The simplest Zend Form Decorator
How to layer Decorators
Rendering Zend Form Decorators individually
Creating composite elements
The simplest way is to do it in the view:
By echoing each element you can print its html. Here's one way to do it:
<form id="<?= $this->form->getId() ?>" action="<?= $this->form->getAction() ?>">
<? foreach ($this->form as $element): ?>
<?= $element ?>
<? if ($element->getName() == 'email'): ?>
<div id="swfupload-control">
<p>Upload upto 5 image files(jpg, png, gif), each having maximum size of 1MB(Use Ctrl/Shift to select multiple files)</p>
<input type="button" id="button" />
<p id="queuestatus" ></p>
<ol id="log"></ol>
</div>
<? endif ?>
<? endforeach ?>
</form>
What this does is it prints all the elements, and puts whatever you have to after the email field. If you add or remove a field from the form this code will continue to work (of course it will fail if you remove the email field).
Related
I haven't used CodeIgniter in nearly a year and I seem to have forgotten a lot of the fundamentals.
I am trying to retrieve the post variables from a form and pass them into a model which inserts them into mysql.
The controller function my form submits to looks like this:
public function validation() {
$this->load->helper("form");
$this->load->model("contact_form");
$data = array(
"name" => $this->input->post("name"),
... etc. etc. ....
);
if ($this->contact_form->new_form($data)) {
$this->load->view("header");
$this->load->view("submitted");
} else echo "Sorry, there was a problem adding the form to the database.";
}
The form in the view is structured like so:
<? echo form_open("form/validation");?>
<div id="one" style="display: block;">
<h1>A Heading</h1>
<p>Some Text</p>
<p class="bold">Name: <input type="text" name="name" class="single" value="<?php echo set_value('name'); ?>"></p>
<p class="bold">Email: <input type="text" name="email" class="single" value="<?php echo set_value('email'); ?>"></p>
<p class="bold">And then some radio buttons</p>
<p> yes <input type="radio" name="registered" value="yes"> no <input type="radio" name="registered" value="no"></p>
<p class="bold">And a textarea...</p>
<textarea name="description" class="fill" value="<?php echo set_value('description'); ?>"></textarea>
next
</div>
<div id="two" style="display:none;">
<h1>Another Heading...</h1>
<p class="bold">And some more textareas</p>
<textarea name="audience" class="fill"></textarea>
... There are four divs in total with further textarea fields ...
<p class="bold"><input type="submit" name="submit" value="submit" class="center"></p>
back
</div>
<? echo form_close();?>
And finally my model is very simple:
class contact_form extends CI_Model {
public function new_form($data) {
$query = $this->db->insert("contact", $data);
if ($query) {
return true;
} else return false;
}
}
The form processes without any errors, but the data just appears as 0's in MySQL. If at any point I attempt to output the value of $_POST it returns BOOL (false), or with $this->input->post('something'); it returns NULL.
You will notice that no actual validation takes place. Initially I was using $this->form_validation->run() and getting the same results. I thought perhaps I was having trouble with the validation so I stripped it out and now I'm fairly certain my problem is that I'm not passing the $_POST variables correctly.
Can anyone explain why I am failing so hard?
I have now resolved this problem.
For some reason <? echo form_open("form/validation");?> was implementing GET and not POST. Replacing that line with <form method="post" accept-charset="utf-8" action="form/validation"/> resolved the issue.
According to the CodeIgniter documentation, by default, form_open should use POST - I have no idea why in my case it decided to use GET.
I am using codeigniter and the tutorial from here. I have made a basic blog tool which works fine. However as it stands to add a new post you have to go to a separate page 'create.php' to get to the form. I would like to try and put the form on the same page as the page that will be updated i.e. 'index.php'. If I try to do this at the moment the form simply refreshes and does submit the data.
model
function insert_post($data){
$this->db->insert('posts', $data);
return;
}
Current View (admin/create.php)
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
View I would like the form to be on (index.php)
<?php
echo '<p>Welcome '.$username.'! All posts available for edit or deletion is listed below.</p><br/>';
echo anchor('admin/create','Create New Post');
$count = count($post['id']);
for ($i=0;$i<$count;$i++)
{
echo '<div class="postDiv">';
echo '<h4>'.$post['title'][$i];
echo '<p>'.$post['summary'][$i].'</p>';
echo '<p>'.$post['content'][$i].'</p>';
//echo anchor('blog/view/'.$post['id'][$i],' [view]');
echo anchor('admin/edit/'.$post['id'][$i],' [edit]');
echo anchor('admin/delete/'.$post['id'][$i],' [delete]</h4>');
echo '</div>';
}
?>
Controller
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $_POST;
$this->posts->insert_post($data);
redirect('admin');
}
}
This was straight forward when I used normal php but with codeigniter I am getting lost with the MVC stuff. I know this is probably a fairly basic question so please either explain your answer or give me a link to something which will explain what I need to do as I want to learn from this. I have read the codeigniter docs on validation but I dont think thats my problem?
What you are trying to do is called embedding a view. I will try to explain how but you should also check some links which might prove to be more in depth:
http://net.tutsplus.com/tutorials/php/an-introduction-to-views-templating-in-codeigniter/
Codeigniter: Best way to structure partial views
The crux of what you need to do is change the link on index.php from:
echo anchor('admin/create','Create New Post');
to
$this->load->view('admin/create');
Now this should work, but to help you on the MVC front, it helps to explain why doing it this way is wrong. The idea of MVC is to seperate the functions in your application into their distinct roles. Most people will frown at putting business logic into views unless it is very minimal. The way that we could improve upon your code is to load the view in the controller, and set it to variable.
At the bottom of the codeigniter docs for views it shows how to load into a variable:
http://ellislab.com/codeigniter/user-guide/general/views.html
if the third parameter of load->view is set to true then the function will return your view as a string instead of outputting it to the browser
$data['input_form'] = $this->load->view('admin/create', $data, true);
then in the view that you want to load that form all you need to do is echo input_form
<?php echo $input_form;?>
So that should solve your problem but there are also a few more things you can do in your view file that will improve the readability of your code.
Instead of using a count() and for loop you can use foreach which makes everything much easier
<?php foreach ($post as $post_item):?>
<div>
<h4><?php echo $post_item['title'];?></h4>
</div>
<?php endforeach;?>
It also helps to break your view files up and have more tags. It might seems like it is extra bloat, but when you have larger view files it will be very cumbersome to continue using as many echo's as you have
just add one method uri_string() in your form action, uri_string will take same url of page put in action you can submit form to same page
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="<?=uri_string()?>" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
in controller little chagnes
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $this->input->post();
$this->posts->insert_post($data);
redirect('admin');
}
}
Use session library
check this another stackoverflow thread to know how to use session
In order to use session library, u need to configure encryption_key in config.php
To do that, check this out
I am new to code igniter. I've created a form but it is not display properly.
When I put
<?php echo form_open('sms'); ?> instead of <form action="">tag
here in my form and controller, I can't understand why it is not displayed.
<?php echo form_open('sms'); ?>
<p>
<label><strong>Username</strong>
<input type="text" name="textfield" class="inputText" id="textfield" />
</label>
</p>
<p>
<label><strong>Password</strong>
<input type="password" name="textfield2" class="inputText" id="textfield2" />
</label>
</p>
<input type="submit" value="Authentification" name="auth" />
<label>
<input type="checkbox" name="checkbox" id="checkbox" />
Remember me</label>
</form>
and my controller is
<?php
class sms extends CI_Controller{
function school(){
$this->load->view('school/index.php');
if($this->input->post('auth',TRUE)){
$this->load->view('school/dashboard.php');
}
else{
$this->load->view('school/index.php');
}
}
}
?>
If this is your entire script for the most part, it looks like you need to load the helper first from the CodeIgniter Form Helper Page.
If you don't have this line, try adding it before the form_open() function:
<?php $this->load->helper('form'); ?>
While I have used CodeIgniter, it's been a while. Let me know if that changes the result.
Edit: Since you've chosen my answer I'll include this one, credits go out to devo:
You could change </form> to: <?php echo form_close(); ?>. There are pros and cons for this method though, and without using arguments you might be better off sticking with </form>.
I'll explain further:
<div class="registration">
<div class="form-box">
<?php $this->load->helper( 'form' ); ?>
<?php $end = '</div></div>'; ?>
<?php echo form_open( 'register' ); ?>
<!-- Form Inputs Here -->
<?php echo form_close( $end ); ?>
<!-- Echos '</form></div></div>' -->
So for closing the form without arguments, the </form> tag works best, both by performance and simplicity. The example used above is a rather simplistic view of what you can do with it, since what I wrote is not very efficient either.
However, this is still php we're talking about, so perhaps the craftier among us could put it to better use.
End Edit
Have you loaded the form helper? You can use $this->load->helper('form'); in your controller action, her inside function school(). You can then use form helper in the view pages.
Load form helper,
$this->load->helper('form');
And use,
echo form_close()
Instead of,
</form>
First in your Controller put in:
$this->load->helper('form');
And Change </form> to :
<?php echo form_close(); ?>
Ok , maybe a hard one to explain. I have a form that is built using PHP Form Builder Class
Which looks like:
$form = new form("firstForm");
$form->setAttributes(array(
"width" => 600,
"noAutoFocus" => 1,
"jsIncludesPath" => "lib/php-form-builder-class/includes",
"action" => "uploader.php"
));
$form->addTextbox("Enter a Title:", 'title' , $row['title']);
$form->addTextbox("Enter a Promo Code:", "promo" , $row['promo']);
$form->addWebEditor("Description", "description", $row['description'], array("basic" => 1));
$form->addWebEditor("Terms and Conditions", "terms", $row['terms'], array("basic" => 1));
$form->addHidden("img_urls", $row['img_urls']);
$form->addHidden("destination", $row['destination']);
$form->addHidden("header", $row['headerimg']);
$form->addHidden("cmd", "submit_0");
$form->addButton();
$form->render();
I want to add some jQuery to one of the elements to allow drag and drop, so I've made another form element:
?>
<form id="firstForm" action="uploader.php" method="post" >
<ul class="sortable">
Mags Select:
<?
foreach ($profiles as $mag) {
?>
<div id="sorty"><input type="checkbox" name="units" value="<? echo $mag ?>" /><label><? echo $mag ?></label><br /></div>
<? } ?>
</ul>
</form>
How can I make the jQuery part post through its values 'units' when the PHP Form Builder Class is submitted?
Ive had a look at adding a method to the class, but wondered if there was an easier way?
EDIT:
The PHP Form Builder Class form is self contained, so wherever the jQuery form is in the page, it will always be outside the other.
You could use javascript and transfer the values from the second form INTO (hidden fields in) the first form?
Or similarly you could just build the form and copy the HTML (view source) and use that instead of the raw php, then slot your jQuery drag and drop thing into it that way.
Just change your second "firstForm" id to secondForm then do something like this:
$('#firstForm').submit(function(event) {
event.preventDefault();
var postData = $(this).add('#secondForm').serialize();
$.post($(this).attr('action'), postData, function() {
// Complete....
}
});
As your units input has multiple elements, you can change this to an array like so (take note of change from units to units[]):
<div id="sorty"> <!-- I assume this should be ouside the foreach... !-->
<? foreach ($profiles as $mag) { ?>
<input type="checkbox" name="units[]" value="<? echo $mag ?>" />
<label><? echo $mag ?></label><br/>
<? } ?>
</div>
Then you'll receive this just like an array in PHP:
foreach ($_POST['units'] as $key => $value)
{
}
Could you not have your jQuery drag-and-drop form field in the same <form> tag as all the other fields? That’s the natural way to do it.
I'm working with a few custom forms, and one of them isn't binding it's values on a POST. I'm using the same logic for each, and only one of them isn't working. Here's the code:
public function executeMediaFileUpload(sfWebRequest $request) {
$this->form = new MediaFileUploadForm();
if (!$request->isMethod('POST'))
$psk = $request->getParameter('psk');
else {
$this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));
$this->logMessage('VALUE: ' . $this->form->getValue('version'));
$psk = $this->form->getValue('application');
}
$this->logMessage('PSK: ' . $psk);
$app = Doctrine::getTable('Application')->find(array($psk));
$this->form->setDefault('application', $app->getPsk());
$this->form->setDefault('version', $app->getVersion()->getLast()->getPsk());
On the initial GET, I can see the value passed in via psk getting set as the default for application in the generated HTML, and all the values show up in the POST request in Firebug, but after I bind the form, it still contains no values.
EDIT:
Yes, the form is setup as multipart and POST. And I'm calling $this->widgetSchema->setNameFormat('values[%s]') in the form.
EDIT2: Here's the HTML for the form, and getName returns "values":
<form name="mediafiles" action="<?php echo url_for('application/mediaFileUpload') ?>" method="POST" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?> id="applications">
<div class="clear">
<div>
<?php echo $form->renderHiddenFields() ?>
<?php foreach($form as $widget): ?>
<?php if (!$widget->isHidden()): ?>
<?php echo $widget->renderLabel() ?>
<?php echo $widget->renderError() ?>
<?php echo $widget->render() ?>
<?php endif ?>
<?php endforeach ?>
</div>
</div>
<!-- Start Bottom Sub Navigation -->
<div class="subnav clear">
Cancel
Upload
</div>
<!-- End Bottom Sub Navigation -->
Check in the code generated on your browser (or firebug) for the form. Form values use to have a name, according to your "name format" configuration, like this:
<input type="text" name="my_name_format[widget_name]" />
So in order to access its value passed to action you must use something like this:
$parameters = $request->getParameter('my_name_format');
$parameter = $parameters['widget_name'];
And like this for each value of your form using "parameters" array.
An simple draft implementing my solution into your code looks like this:
public function executeMediaFileUpload(sfWebRequest $request) {
$this->form = new MediaFileUploadForm();
$parameters = $request->getParameter('values'); // Since you used $this->widgetSchema->setNameFormat('values[%s]')
if (!$request->isMethod('POST'))
$psk = $parameters['psk'];
else {
$this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));
$this->logMessage('VALUE: ' . $parameters['version']);
$psk = $parameters['application'];
}
$this->logMessage('PSK: ' . $psk);
$app = Doctrine::getTable('Application')->find(array($psk));
$this->form->setDefault('application', $app->getPsk());
$this->form->setDefault('version', $app->getVersion()->getLast()->getPsk());
Hope this solution works.