Yii2 use form tags - forms

When I submit my form i got some errors,
This is my form script which contains posted fields.
<?php $form = ActiveForm::begin([
'action'=>'userpermission/create',
]); ?>
<form method="post" action="<?php echo Yii::$app->getUrlManager()->createUrl('admin/userpermission/create')?>">
<ul class="list-unstyled">
<li>
<?= $form->field($model, 'idPermission')->checkboxList(ArrayHelper::map(Permission::find()->all(),"idPermission", "libelle", [
'onclick' => "$(this).val( $('input:checkbox:checked').val());",
'item' => function($index, $label, $name, $checked, $value) {
return "<label class='ckbox ckbox-primary col-md-4'><input type='checkbox' {$checked} name='{$name}' value='{$value}' tabindex='3'>{$label}</label>";
}
])) ?>
</li><br>
</ul>
<div class="form-group">
<?php Html::submitButton($model->isNewRecord ? 'Valider' : 'Create' ,['class' => $model->isNewRecord ? 'btn btn-primary','value'=>'Create', 'name'=>'submit']) ?>
</div>
<?php ActiveForm::end(); ?>
and my create function looks like but i got the error undefined variable model!
public function actionCreate()
{
$model = new Userpermission();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
print_r(Yii::$app->request->post());
exit;
return $this->redirect(['index', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}

1st off, you dont need that <form> tag.
<?php $form = ActiveForm::begin([
'action'=>'userpermission/create',
]); ?>
creates and initializes the form for you with corresponding client-validations.
the possible issue is due to unclosed </form> which anyways is unnecessary.
suggesting to remove the <form> tag entirely. and try again and if any issue please let me know the error.
also bring the print_r(Yii::$app->request->post()); before if condition.
enable error reporting in your function
error_reporting(E_ALL);
please give the filename to code block. it would be easier to understand that way.

Related

cakephp3- unable to post form data to controller function

I have a contact us form and user enter data and submits it. This data needs to accessed in controller function so I can send a mail to admin informing about the user request recently received.
But when I press submit button, nothing happens. Form just reloads and the contactus form (view page) is shown to the users. I don't know why the data is not getting passed to the controller function.
I'mm new to CakePHP framework and I'm using CakePHP3 for development purposes.
Here is my form:
<?php echo $this->Form->create(null, ['url' => ['controller' => 'Pages', 'action' => 'contactus']]); ?>
<div class="col-md-6">
<?php echo $this->Form->input('fname', ['placeholder' => 'Your name.' , 'id' => 'fname', 'required' => 'required']); ?>
</div>
<div class="col-md-6">
<?php echo $this->Form->input('mail', ['placeholder' => 'Your email.' , 'id' => 'mail', 'required' => 'required']); ?>
</div>
<div class="col-md-6">
<?php echo $this->Form->input('subject', ['placeholder' => 'Write something.', 'id' => 'subject']); ?>
</div>
<div class="col-md-9">
<?php echo $this->Form->button(__('Submit')); ?>
</div>
<?php echo $this->Form->end(); ?>
And my controller function is:
public function contactus()
{
$pages ='';
if ($this->request->is('post'))
{
$pages = $this->request->data('Contact');
}
$this->set(compact('pages'));
$this->set('_serialize', ['pages']);
}
Can anyone tell me the mistakes I made?
I think your form is submitting but not through the post method. So I would like to say you that, please make the bellow changes before submitting the form.
$pages ='';
if ($this->request->is('post'))
{
echo "Request is post";die;
$pages = $this->request->data('Contact');
}else{
echo "request is not post";die;
}
$this->set(compact('pages'));
$this->set('_serialize', ['pages']);
Now check, which is printing in the display. Then I can help you further.
Remember: - fill the form, then after change the controller method, then press submit method.

Can't validate form CakePHP 3

I'm new on CakePHP and I can't validate a login form. I'm getting the following error: Notice (8): Undefined variable: user [APP/Template\Users\login.ctp, line 5]
I already tried to use this code: <?= $this->Form->create('User'); ?> The error is removed but the validation doesn't works.
Can someone help me?
login.ctp:
<br>
<div class="index large-4 medium-5 large-offset-4 medium-offset-4 columns">
<div class="panel">
<h2 class="text-center">Login</h2>
<?= $this->Form->create($user); ?>
<?php
echo $this->Form->input('email');
echo $this->Form->input('password');
?>
<?= $this->Form->submit('Login', array('class' => 'button')); ?>
<?= $this->Form->end(); ?>
</div>
</div>
login function - UsersController.php:
// Login
public function login()
{
if($this->request->is('post'))
{
$user = $this->Auth->identify();
if($user)
{
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'comentario']);
}
// Erro no Login
$this->Flash->error('Erro de autenticaĆ§Ć£o');
}
}
First of all, change this line
<?= $this->Form->create($user); ?>
to this
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
Then, you can simplify your submit like this
<?= $this->Form->button(__('Login')); ?>
Make sure you create UsersTable.php in you src/Model/Table and put this code
// src/Model/Table/UsersTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('username', 'A username is required')
->notEmpty('password', 'A password is required')
}
}
It's not good using redirect the specific controller inside login method. Change it:
return $this->redirect($this->Auth->redirectUrl());
Then tell your Auth Component where user should be redirect after login
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Articles',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
And the most important. Read Authentication and Authorization Tutorial

Codeigniter validate form is not working

I have the same implementation for my login for and is working, but on my contact form it is not, and I have no error message just re routed to the home page.
the weird thing is if in my controller i implement the index function like this:
public function index() {
$this->myprocess();
}
and my view using
<?php
$attributes = array('class' => 'form-contact', 'id' => 'myform2');
echo form_open('contact',$attributes);
?>
instead of calling my function myprocess all the validations work but no use for a form with out my header footers etc.
bellow that is how i want my code to work i hope yall can help me.
my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class contact extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('contact_m');
}
public function index()
{
$data = array('title' => 'Contact', 'main_content' => 'contact_v');
$this->load->view('template', $data);
}
public function myprocess(){
$this->form_validation->set_rules('dfname', 'Name', 'required|trim|xss_clean|max_length[40]');
$this->form_validation->set_rules('dfemail', 'Email', 'required|trim|xss_clean|valid_email|max_length[50]|callback__verifyemail');
$this->form_validation->set_rules('dfmsg', 'dfmsg', 'trim|xss_clean');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('contact_v');
}
else
{
$form_data = array(
'dfname' => set_value('dfname'),
'dfemail' => set_value('dfemail'),
'dfmsg' => set_value('dfmsg')
);
if ($this->contact_m->SaveForm($form_data) == TRUE)
{
redirect('contact/success');
}
else
{
echo 'An error occurred saving your information. Please try again later';
}
}
}
function success()
{
echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';
}
public function verifyemail(){
$name = $this->input->post('dfName');
$pass = $this->input->post('dfemail');
if($this->contact_m->email_exist($name,$pass)){
if ($this->session->userdata('site_lang') == 'portuguese')
{
$this->form_validation->set_message('_verifyuser','Usuario Inexistente!');
}else{
$this->form_validation->set_message('_verifyuser','User Not Found!');
}
$this->index();
return false;
}else{
return true;
}
}
}
?>
my view:
<div class="container">
<div class="row">
<div class=" col-md-4 col-md-offset-4">
<?php echo br(2)?>
<div class="account-wall drop-shadow">
<?php
$title = $this->my_library->my_title($this->session->userdata('site_lang'),FORM_CONTACT);
echo '<h1 class="text-center login-title">'. $title. '</h1>';
echo br(1)
?>
<?php
$attributes = array('class' => 'form-contact', 'id' => 'myform2');
echo form_open('contact/myprocess',$attributes);
?>
<p>
<label for="dfname">Name</span></label>
<?php echo form_error('dfname'); ?>
<input id="dfname" type="text" class="form-control" placeholder="Name" name="dfname" maxlength="40" value="<?php echo set_value('dfname'); ?>" autofocus />
<?php echo br(1)?>
</p>
<p>
<label for="dfemail">Email</span></label>
<?php echo form_error('dfemail'); ?>
<input id="dfemail" type="text" class="form-control" placeholder="Email" name="dfemail" maxlength="50" value="<?php echo set_value('dfemail'); ?>" />
<?php echo br(1)?>
</p>
<p>
<label for="dfmsg">Message</label>
<?php echo form_error('dfmsg'); ?>
<?php echo form_textarea( array( 'name' => 'dfmsg', 'rows' => '4', 'cols' => '43', 'value' => set_value('dfmsg') ) )?>
<?php echo br(1)?>
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php form_close();?>
</div>
</div>
</div>
</div>
<?php echo br(5)?>
your callback function for validation need an underscore for prefix name :
public function _verifyemail()
and you need to call the process function :
public function index()
{
$data = array('title' => 'Contact', 'main_content' => 'contact_v');
if($this->input->post())
$this->myprocess();
$this->load->view('template', $data);
}
So after all this days and examining all my code and re-writing all of it i found the problem.
for some reason this line wasnt working : echo form_close(); so my first form was aways open messing up asll my validation after writing on all of then it starting working.

Zend Framework Custom Forms with viewScript

I am having some problems working out how to use custom forms in Zend Framework.
I have followed various guides but none seem to work. Nothing at all gets rendered.
Here is the bits of code that I am trying to use (All code below is in the default module). I have simplified the code to a single input for the test.
applications/forms/One/Nametest.php
class Application_Form_One_Nametest extends Zend_Form {
public function init() {
$this->setMethod('post');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Box Name')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Submit Message');
$submit->setAttrib('id', 'submitbutton');
$submit->setAttrib('class', 'bluebutton');
$this->addElements(array($name, $submit));
}
}
application/views/scripts/one/formlayout.phtml
<form action="<?= $this->escape($this->form->getAction()) ?>" method="<?= $this->escape($this->form->getMethod()) ?>">
<p>
Please provide us the following information so we can know more about
you.
</p>
<? echo $this->element->name ?>
<? echo $this->element->submit ?>
</form>
application/controllers/IndexController.php
public function formtestAction() {
$form = new Application_Form_One_Nametest();
$form->setDecorators(array(array('ViewScript', array('viewScript' => 'one/formlayout.phtml'))));
$this->view->form = $form;
}
application/views/scripts/index/formtest.phtml
<h1>Formtest</h1>
<?
echo $this->form;
?>
The above code does not throw any errors or render any part of formlayout.phtml including the form tags or text between the p tags.
Can anybody tell me what I might be doing wrong?
I think the problem is your form element's decorator. You should set the decorator to ViewHelper and Error only. It works for me at least.
Here is the code I used and it should work
applications/forms/Form.php
class Application_Form_Form extends Zend_Form {
public function loadDefaultDecorators() {
$this->setDecorators(
array(
array(
'ViewScript',
array(
'viewScript' => 'index/formlayout.phtml',
)
)
)
);
}
public function init() {
$this->setAction('/action');
$this->setMethod('post');
$this->addElement('text', 'name', array(
'decorators' => array('ViewHelper', 'Errors')
));
}
}
application/views/scripts/index/formlayout.phtml
<form action="<?php echo $this->element->getAction(); ?>" method="<?php echo $this->element->getMethod(); ?>">
<div>
<label for="name">Box Name</label>
<?php echo $this->element->name; ?>
</div>
<input type="submit" value="Submit Message" id="submitbutton" class="bluebutton">
</form>
application/views/scripts/index/index.phtml
<!-- application/views/scripts/index/index.phtml -->
<?php echo $this -> form; ?>
application/controllers/IndexController.php
public function indexAction() {
$form = new Application_Form_Form();
$this -> view -> form = $form;
}
Here is a very simple example to get you going adapted from this article.
The form:-
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setMethod('POST');
$this->setAction('/');
$text = new Zend_Form_Element_Text('testText');
$submit = new Zend_Form_Element_Submit('submit');
$this->setDecorators(
array(
array('ViewScript', array('viewScript' => '_form_test.phtml'))
)
);
$this->addElements(array($text, $submit));
$this->setElementDecorators(array('ViewHelper'));
}
}
The order in which setDecorators(), addElements() and setElementDecorators() are called is very important here.
The view script _form_test.phtml can be called anything you like, but it needs to be in /views/scripts so that it can be found by the renderer.
/views/scripts/_form_test.phtml would look something like this:-
<form id="contact" action="<?php echo $this->element->getAction(); ?>"
method="<?php echo $this->element->getMethod(); ?>">
<p>
Text<br />
<?php echo $this->element->testText; ?>
</p>
<p>
<?php echo $this->element->submit ?>
</p>
</form>
You instantiate the form, pass it to the view and render it as usual. The output from this example looks like this:-
<form id='contact' action='/' method='post'>
<p>
Text<br />
<input type="text" name="testText" id="testText" value=""></p>
<p>
<input type="submit" name="submit" id="submit" value="submit"></p>
</form>
That should be enough to get you started creating your own forms.
Usually, if you don't see anything on the screen it means that some sort of error happened.
Maybe you have errors turned off or something, maybe not. I'm just trying to give you ideas.
The only things I could spot where the following.
In the below code, you have to still specify the form when trying to print out the elements.
<form>
action="<?php $this->escape($this->element->getAction()) ?>"
method="<?php $this->escape($this->element->getMethod()) ?>" >
<p>
Please provide us the following information so we can know more about
you.
</p>
<?php echo $this->element->getElement( 'name' ); ?>
<?php echo $this->element->getElement( 'submit' ) ?>
</form>
As vascowhite's code shows, once you are inside the viewscript, the variable with the form is called element. The viewscript decorator uses a partial to do the rendering and thus it creates its own scope within the viewscript with different variable names.
So, although in your original view it was called $form, in the viewscript you'll have to call it element.
Also, maybe it was copy/paste haste, but you used <? ?> tags instead of <?= ?> or <?php ?> tags. Maybe that caused some error that is beyond parsing and that's why you got no output.

select menu default values not rendering in symfony

I am using Symfony 1.4, and am using embedded forms to place multiple similar forms into one form for a configuration page. I am having success showing the form, but the default values of the sfWidgetFormChoice widgets are not being rendered, i.e. the selected="selected" attribute is gone from the HTML.
Incidentally, the default values show up if I don't use embedded forms. The problem with avoiding embedded forms is that each form has identical inputs and therefore overwrites itself.
The action code is as such, some code omitted for brevity:
$serviceFormArray = array();
$this->fullForm = new ConfigForm();
foreach($this->serviceArray as $net => $service)
{
$this->partialForm = new ConfigForm();
foreach($service as $typeId => $val)
{
$typeObj = Doctrine::getTable('Type')->find($typeId);
$typeField = new sfWidgetFormChoice(array(
'default' => $val,
'choices' => array('1' => 'on', '0' => 'off'),
'label' => $typeObj->name)
);
$typeField->setDefault($val);
$serviceFormArray[$typeObj->name] = $typeField;
}
$netObj = Doctrine::getTable('Network')->find($net);
$this->partialForm->setWidgets($serviceFormArray);
$this->fullForm->embedForm($netObj->name,$this->partialForm);
}
and the template looks like this, some code omitted for brevity:
<div class="sectionBox">
<?php echo $fullForm->renderFormTag('/configure/submitconfig') ?>
<?php foreach ($fullForm->getVisibleFields() as $part => $field): ?>
<div class="settingsField">
<?php echo $field->renderLabel() ?>
<?php echo $field->render() ?>
<input type="hidden" name="plug" value="<?php echo $plugName; ?>"/>
</div>
<?php endforeach; ?>
<div id="submitConfig"><input type="submit" value="Save"/></div>
</form>
</div>
Try setting default value via $form->setDefault($name, $default).
$this->partialForm->setDefault($typeObj->name, $val);