Why is CakePHP 2.3.0 adding a '1' to my Form Post Values? - forms

I'm using cakephp 2.3.0. I searched in the manual for quite awhile, but I haven't found the answer. Also, I've searched the Internet, but still haven't found what I'm looking for. SO, I'm posting my question here. Note, I'm fairly new to cakephp.
Scenario:
I have a simple form with two fields: activity and zip code.
I'm using POST on the form.
When I type in some value in those fields and submit, I echo those 'post' values/parameters and display in the browser screen. What I typed in, I can see on the screen, but the number '1' is added to the end of what I typed in the form.
Here is an example. I type in these values in the form, 'walk' and '44555'. Then I click 'Submit'. The post goes to my controller's action, which then calls my view. My view is displayed on the browser screen and I echo out those 'post' values. The results on screen are 'walk1' and '445551'.
Example #2: If I follow the steps above and don't enter any values in my form (I'll add error checking later), what I see on the browser screen is '1' and '1'.
I am unable to figure out why I am getting the value of '1' added to my form's POST values?
I'll be glad to include any other additional php code to this posting, if requested by someone trying to help.
Here is my FORM code (from my view)...I know there are DIV helpers, but I'll get to that later:
echo $this->Form->create(null, array('url' => array('controller'=>'activities', 'action'=>'results'))); ?>
<div class="box1" style="position:relative; top:10px; left:10px; float: left;">
Search here.... <br>
<hr>
<?php echo $this->Form->input('activityName', array('size'=>'30',
'label'=>'Activity Name:', 'value'=>'i.e. walking, etc.'));?>
<br>
<?php echo $this->Form->input('zip', array('size'=>'7', 'label'=>'Postal Code:')); ?>
<br>
</div>
<div class="box1" align="right">
<?php echo $this->Form->end('Go Search');?>
</div>
Here is my controller code:
<?php
class ActivitiesController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
//other code....
}
public function results() {
$this->layout = 'second';
$name = $this->request->data['Activity']['activityName'];
$pCode = $this->request->data['Activity']['zip'];
$this->set('theName', $name);
$this->set('theZip', $pCode);
$this->set('results', $this->Activity->
find('all', array('conditions' => array('name' => $name, 'postal_code' => $pCode))));
$this->set('title_for_layout', 'Results');
$this->render();
}
}
?>
My final view code. I left off some of the code...just showing the part that matters:
<div style="position:relative; top:10px; left:5px; ">
<?php echo print_r($theName); ?>
<br>
<?php echo print_r($theZip); ?>
Thanks

The 1 comes from printing the return value of print_r() which is true (i.e. 1).
In other words: you shouldn't do echo print_r(), just do print_r(). The function handles the printing by itself, you don't have to print the results manually.
(Also, print_r() is almost never the best choice to print out values except when debugging and even then CakePHP's debug() is much more suitable.)

Related

Open FPDF in new tab

I have a pdf generated (fpdf) from a post form. I would like the pdf to open in a new tab and/or window prompting the user to save the pdf. I'm guessing I need to save the output to a string
$data=$pdf->Output("OfficeForm.pdf", "S");
but what exactly can I do with this string to get it to open in a new window. I've attempted something like this but it's not working. Am I on the right track or is window.open not what I need?
echo "<script type=\"text/javascript\">
window.open('$data', '_blank')
</script>";
If you use a form you can do it by specifying target='_blank' in the -tag (next to where you should have submit='something')
Example:
This will open a new Tab (showing whatever "makepdf.php" produces) on submit.
Hope it answers the question correctly
I simply added target="_blank" to my form opening tag and used $_SESSION[]; to pass my form to the FPDF code:
<?php session_start(); ?>
<form id ="buildPDFform" name="buildPDFform" target="_blank" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
...some code for my form
<input type="submit" name="buildPDf" id="buildPDf" class="buildPDFbutton" value="Build the PDF">
</form>
Then when the form is submitted I gather my form items, put them in an array, create a session the array goes into and use a header("Location: testcode.php") to redirect to where my FPDF code is.
if (isset($_POST['buildPDf'])) {
$pdfArray = array();
foreach ($_POST as $key => $value) {
...gather your form items into your array
}
$_SESSION['pdfArray'] = $pdfArray;
header("Location: testcode.php");
}
And don't forget in your FPDF code file (testcode.php in my case) to grab your session that has the array.
<?php
session_start();
$pdfArray = $_SESSION['pdfArray'];
... your FPDF code
$pdf->Output('I');
?>
source: https://www.thesitewizard.com/html-tutorial/open-links-in-new-window-or-tab.shtml
use target="_blank" in your a tag to open it to new tab
Try $pdf->Output("OfficeForm.pdf", "I");

Joomla 2.5 - component development - using form

I am trying to add some form to my component, but I am not shure what naming conventions must be applied to work it correctly.
Currently I have a working form - it displays fields stored in XML file and loads data from database to it. However, when i try to submit this form (edit or add new records), it doesn't work. After pressing submit (save() method) it just redirects me and displays that record was edited successfuly but it wasn't. When I try to edit existing record, after pressing submit nothing happens and when I try to add new record, it just adds empty/blank record.
So I was doing a little debug and discovered, that problem is in the JController::checkEditId() method. It always returns false which means that JControllerForm::save() returns false as well and that's why it doesn't save it correctly. HTML code of form is correct and I can access the data by using global array $_POST.
I suspect that this problem is because of naming conventions in methods loadFormData, getForm of JModelAdmin class. I am not sure how to name that form.
So here is my code related to this problem:
Subcontroller for displaying the form - controllers/slideshowform.php
class SlideshowModelSlideshowForm extends JModelAdmin{
public function getForm($data = array(), $loadData = true){
return $this->loadForm('com_slideshow.slideshowform', 'editform', array('load_data' => $loadData, 'control' => 'jform'));
}
protected function loadFormData(){
$data = JFactory::getApplication()->getUserState('com_slideshow.edit.slideshowform.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
public function getTable($table = "biometricslideshow"){
return parent::getTable($table);
}
}
views/slideshowform/view.html.php
class SlideshowViewSlideshowForm extends JView{
public function display($tmpl = null){
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
$this->form = $this->get('form');
$this->item = $this->get('item');
JToolBarHelper::save('slideshowform.save');
parent::display();
}
}
views/slideshowform/tmpl/default.php
<?php
defined('_JEXEC') or die('Restricted access');
JHtml::_('behavior.tooltip');
?>
<form method="post" action="<?php echo JRoute::_("index.php?option=com_slideshow&id=".(int) $this->item->id)?>" name="adminForm" id="slideshow-form">
<fieldset class="adminform">
<legend>Edit slide</legend>
<table>
<input type="hidden" name="task" value="">
<?php echo JHtml::_('form.token'); ?>
<?php
foreach($this->form->getFieldset() as $field){
?>
<tr><td><?php echo $field->label ?></td><td><?php echo $field->input ?></td></tr>
<?php
}
?>
</table>
</fieldset>
</form>
Can someone take o look, please?
you have to add controller SlideshowControllerSlideshowForm and code save method. In there you have to validate the form data and call SlideshowModelSlideshowForm->save event, then redirect with success/failure message.

calling echo $this->action('panLogin','user') and $this->action('panRegister','user') on same script

I have a problem, i'm trying to render 2 forms (login and register) on one layout scrpt (header.phtml), every time i submit on one of the forms both actions for the controller are getting fired and i'm unsure how to fix it.
The forms are getting rendered fine within the layout, however when you click 'Login' or 'Register' on the forms the code fires in both the 'login' and 'register actions.
the header layout script snippet:-
<div class="left">
<h1>Already a member? <br>Then Login!</h1>
<?php
echo $this->action('panlogin', 'user');
?>
</div>
<div class="left right">
<h1>Not a member yet? <br>Get Registered!</h1>
<?php
echo $this->action('panregister', 'user');
?>
</div>
the action scripts (phtmls)
panregister.phtml
<div id="pan-register">
<?php
$this->registerForm->setAction($this->url);
echo $this->registerForm;
?>
</div>
panlogin.phtml
<div id="pan-login">
<?php
$this->loginForm->setAction($this->url);
?>
</div>
the user controller actions:-
class Ajfit_UserController extends Zend_Controller_Action
{
protected $_loginForm;
protected $_registerForm;
public function init()
{
$this->_loginForm = new Ajfit_Form_User_Login(array(
'action' => '/user/login',
'method' => 'post',
));
$this->_registerForm = new \Ajfit\Form\User\Registration(array(
'action' => '/user/register',
'method' => 'post'
));
}
//REGISTER ACTIONS
public function panregisterAction(){
$this->registerAction();
}
public function registerAction(){
$request = $this->_request;
if ($this->_request->isPost()){
$formData = $this->_request->getPost();
}
$this->view->registerForm = $this->_registerForm;
}
//LOGIN ACTIONS
public function panloginAction(){
$this->loginAction();
}
public function loginAction(){
$request = $this->_request;
if(!$auth->hasIdentity()){
if ($this->_request->isPost()){
$formData = $this->_request->getPost();
}
}
$this->view->loginForm = $this->_loginForm;
}
}
Please can someone with a little more knowlegde with the action('act','cont'); ?> code with in a layout script help me out with this problem.
Thanks
Andrew
While David is correct where best practices are concerned, I have on occasion just added another if() statement. Kinda like this:
if ($this->getRequest()->isPost()) {
if ($this->getRequest()->getPost('submit') == 'OK') {
just make sure your submit label is unique.
Eventually I'll get around to refactoring all those actions I built early in the learning process, for now though, they work.
Now to be nosy :)
I noticed: $formData = $this->_request->getPost(); while this works, if you put any filters on your forms retrieving the data in this manner bypasses your filters. To retrieve filtered values use $formData = $this->getValues();
from the ZF manual
The Request Object
GET and POST Data
Be cautious when accessing data from the request object as it is not filtered in any way. The router and
dispatcher validate and filter data for use with their tasks, but
leave the data untouched in the request object.
From Zend_Form Quickstart
Assuming your validations have passed, you can now fetch the filtered
values:
$values = $form->getValues();
Don't render the actions in your layout. Just render the forms:
<div class="left">
<h1>Already a member? <br>Then Login!</h1>
<?php
echo new \Ajfit\Form\User\Login(array(
'action' => '/user/login',
'method' => 'post'
));
?>
</div>
<div class="left right">
<h1>Not a member yet? <br>Get Registered!</h1>
<?php
echo new \Ajfit\Form\User\Registration(array(
'action' => '/user/register',
'method' => 'post'
));
?>
</div>
Then, whichever form gets used will post to its own action.

Form validation problem with CodeIgniter

I have this view:
<?php echo form_open(); ?>
<?php echo form_input('username', '', ''); ?>
<?php echo form_submit('submit', 'Submit'); ?>
<?php echo form_close(); ?>
<?php echo validation_errors(); ?>
and this controller method:
function test() {
$username = $this->input->post('username');
$this->form_validation->set_rules($username, 'Username', 'required|min_length[4]');
if ($this->form_validation->run() !== FALSE) {
echo 'Tada!';
}
$this->load->view('test');
}
but when I leave the username field blank, nothing happens. However, if I type in something in it will tell me the field is required. I've downloaded and given CI a fresh install almost ten times now, trying to load with and without different helpers etc. It's becoming really frustrating, please help.
Try using this:
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');
The problem lies in the first parameter of set_rules, which is the field name.
The $username you're passing is basically setting the field name to validate as whatever the user puts in the input field. If you were to type 'username' into the input box, you'd see that your form validates.
Change the line
$this->form_validation->set_rules($username, 'Username', 'required|min_length[4]');
to
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');
Maybe is the problem of this line
<?php echo form_open(); ?>
If you leave it blank it basically send back to the controller itself and calling the construct and index function only. In this case your function dealing with form processing is "test()"
try this
<?php echo form_open('yourControllerName/test'); ?> //test is the function dealing with
if it is not working try on this
<?php echo form_open('test'); ?>

symfony 1.2 forms renderRow error message problem

Im trying to render a row field in a template with some extra styles, like this:
<?php echo $form['email']->renderRow(array('class' => 'text')) ?>
<?php echo $form['email']->renderError() ?>
The problem occurs when my form doesnt validate on this field... then it displays the error message 2 times!, i.e the renderRow renders one errorMsg string, and the renderError does it again... How can i stop renderRow from displaying the error message?
If I just do this, then it works:
<?php echo $form['email'] ?>
But in that case I cant style the field as I want....
thanks!
I am pretty sure this is also valid for 1.2. Instead of using renderRow, use something like this:
<?php echo $form['FormElementName']->renderLabel() ?> //display form element label
<?php echo $form['FormElementName']->renderError() ?> //display form element error (if exist)
<?php echo $form['FormElementName']->render(array('class' => 'text')); ?> //display form element
renderRow does them all at once.
EDIT From comments (Flask) - added ->render(array('class' => 'text'));