calling zend form to AuthenticationController error - zend-framework

this is my form script: located in application/forms and i copy it form here and by the way im using xampp
class Form_LoginForm extends Zend_Form
{
public function init()
{
$username = $this->addElement('text', 'username', array(
'filters' => array('StringTrim', 'StringToLower'),
'validators' => array(
'Alpha',
array('StringLength', false, array(3, 20)),
),
'required' => true,
'label' => 'Your username:',
)); ect.////
}
and this my authentication script.. located in application/controller:
class AuthenticationController extends Zend_Controller_Action {
public function loginAction()
{
$form = new Form_LoginForm(); // doest work
$this->view->form = $form;
$myDb = $this->getAuthAdapter();
$userName = 'user';
$password = 'ds';
$myDb->setIdentity($userName)
->setCredential($password);
}
private function getAuthAdapter(){
$myDb = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$myDb->setTableName('zuser')
->setIdentityColumn('table1')
->setCredentialColumn('table2');
return $myDb;
}
}
i want to call the class form Form_LoginForm inside the AuthenticationController but it gives me and error: *Fatal error: Class 'Form_LoginForm' not found in C:\xampp\htdocs\zendframework\sampleSite\application\controllers\AuthenticationController.php on line 18*
my question is what is the right way to call a class forms.. and where is the __autoload located?

Try changing class Form_LoginForm extends Zend_Form into class Application_Form_LoginFrom extends Zend_Form and then in you're AuthController $form = new Application_Form_LoginForm

Related

How to add data transformer inside a event listener

So, here's my problem: I have to add a field to a form based on it's underlying data but i've to add a data transformer to the field.
I thought the solution will be simple, just add a PRE_SET_DATA event listener to the form (just to access to the underlying data) and add the field and the transformer inside the listener. But i can't add the transformer inside the listener because the form is already locked.
I´ve tried many workarounds but i couldn't solved it. Her's my code:
$builder->...
->add(
$builder->create('date', 'choice', array(
'label' => 'form.game.date',
'empty_value' => 'form.game.date',
'required' => false,
'choices' => array(
'2014-04-10' => '10/Apr', // just to test
'2014-04-11' => '11/Apr',
)
))
->addModelTransformer(new DateToStringTransformer())
);
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($builder) {
$game = $event->getData();
$form = $event->getForm();
$period = new \DatePeriod(
$game->getTournament()->getBeginDate(),
new \DateInterval('P1D'),
$game->getTournament()->getEndDate()->add(new \DateInterval('P1D'))
);
$dates = array();
foreach($period as $date){
$dates[$date->format("Y-m-d")] = $date->format("j/M");
}
$form->add('date', 'choice', array(
'label' => 'form.game.date',
'choices' => $dates,
));
});
When i add the date field to the form inside event listener, the previously added data field is replaced so it's data transformer...
Is there a way to do it?
I wrote some test and updated your code a bit. Check if i understand your question correctly.
SomeTypeTest.php:
<?php
class SomeTypeTest extends TypeTestCase
{
/**
* #test
*/
public function testSubmitValidData()
{
$begin = new \DateTime();
$formData = array(
'date' => '2014-01-15'
);
$type = new SomeType();
$form = $this->factory->create($type);
$form->submit($formData);
$this->assertTrue($form->isSynchronized());
$this->assertEquals(['date' => \DateTime::createFromFormat('Y-m-d', '2014-01-15')], $form->getData());
$view = $form->createView();
$children = $view->children;
foreach (array_keys($formData) as $key) {
$this->assertArrayHasKey($key, $children);
}
}
}
SomeType.php:
<?php
class SomeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($builder) {
//$game = $event->getData();
$form = $event->getForm();
$period = new \DatePeriod(
\DateTime::createFromFormat('Y-m-d', '2014-01-01'), // for test
new \DateInterval('P1D'),
\DateTime::createFromFormat('Y-m-d', '2014-01-30') // for test
);
$dates = array();
foreach ($period as $date) {
$dates[$date->format("Y-m-d")] = $date->format("j/M");
}
$form->add($builder->create('date', 'choice', array(
'label' => 'form.game.date',
'empty_value' => 'form.game.date',
'auto_initialize' => false,
'required' => false,
'choices' => $dates
))
->addModelTransformer(new DateToStringTransformer())->getForm()
);
});
}
public function getName()
{
return 'st';
}
}
DateToStringTransformer.php:
<?php
class DateToStringTransformer implements DataTransformerInterface
{
/**
* #param mixed $value
* #return mixed|void
*/
public function transform($value)
{
if (!$value) {
return null;
}
return $value->format('Y-m-d');
}
/**
* #param mixed $value
* #return mixed|void
*/
public function reverseTransform($value)
{
return \DateTime::createFromFormat('Y-m-d', $value);
}
}
https://gist.github.com/ChubV/11348928
I've managed to get it work by creating a custom type that always add the data transformer. Then i can call "form->add('date', 'my_type',..)" from any event listener without loosing the data transformer.
MyType.php
class MyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('field1')
->add('field2')
...;
$builder->addEventSubscriber(new AddDateSubscriber());
}
}
CustomType.php
class DateChoiceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer(new DateToStringTransformer());
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'invalid_message' => 'The selected date does not exist',
));
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'date_choice';
}
}
Every time i add a date_choice type to a form the data transformer will be added too.
class AddDateSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(FormEvent $event)
{
$game = $event->getData();
$form = $event->getForm();
$endDate = \DateTime::createFromFormat('Y-m-d', $game->getTournament()->getEndDate()->format('Y-m-d'));
$period = new \DatePeriod(
$game->getTournament()->getBeginDate(),
new \DateInterval('P1D'),
$endDate
);
$dates = array();
foreach($period as $date){
$dates[$date->format("Y-m-d")] = $date->format("j/M");
}
$form->add('date', 'date_choice', array(
'label' => 'form.game.date.label',
'empty_value' => 'form.game.date.none',
'required' => false,
'choices' => $dates,
));
}
}
DateToStringTransformer.php
class DateToStringTransformer implements DataTransformerInterface
{
public function transform($date)
{
if (null === $date) {
return "";
}
return $date->format("Y-m-d");
}
public function reverseTransform($stringDate)
{
if (!$stringDate) {
return null;
}
$date = \DateTime::createFromFormat('Y-m-d', $stringDate);
if (false === $date) {
throw new TransformationFailedException('Sting to date transformation failed!');
}
return $date;
}
}
Hope that this will help someone.

How to pass params from controller to Zend_Form?

I know this question is already answered here. But this doesnt work for me.
The Form is generated by using the PluginLoader:
$formClass = Zend_Registry::get('formloader')->load('Payment');
$form = new $formClass(array('someval' => $my_arr));
Payment.php:
class Form_Payment extends Zend_Form
{
protected $_someval = array();
public function init()
{
$this->setAction('payment/save');
//....
$this->addElement('multiCheckbox', 'store_id', array('label' => 'Someval:', 'required' => true, 'multiOptions' => $this->getSomeval()))
}
public function setSomeval($someval) {
$this->_someval = $someval;
}
public function getSomeval() {
return $this->_someval;
}
}
As I can see the load method only returns the class name, so new $formClass(); is equal new Form_Payment() but why this isn't accept params?
Ok I found a way by myself. I was looking for a way to inject some params while my Zend_Form was initialised. It seems the only way for this is to pass the params to the constructor - which is executed before the init method.
class Form_Payment extends Zend_Form
{
private $_someval;
public function __construct(array $params = array())
{
$this->_someval = $params['someval'];
parent::__construct();
}
public function init()
{
$this->setAction('payment/save');
//....
$this->addElement('multiCheckbox', 'store_id',
array('label' => 'Someval:',
'required' => true,
'multiOptions' => $this->_someval // passed params now available
))
}
}
You can add custom function to your form class like
class Form_Payment extends Zend_Form
{
public function init()
{
$this->setAction('payment/save');
// and so on
}
public function doSome()
{
$this->setAction('other/action');
}
}
and call it after instanciating form in controller
$form = new $formClass();
$form->doSome();

Class Not Found in Zend Framework

I have installed a fresh copy of zend framework 1.11.11 on my local workstation (Windows). For my admin module I have created "Login.php" form under /application/modules/admin/models/Form/Login.php I have also set up autoloader in Bootstrap.php Like
protected function _initAutoloader()
{
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('My_');
new Zend_Application_Module_Autoloader(array(
'basePath' => APPLICATION_PATH,
'namespace' => 'Default')
);
$loader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH.'/models/',
'namespace' => '')
);
$loader->addResourceType('forms', 'Form/', 'Form');
return $autoloader;
}
on my loginAction() method of IndexController.php file of admin module, i am using
$form = new Admin_Model_Form_Login();
But Getting below error:-
Fatal error: Class 'Admin_Model_Form_Login' not found in
C:\wamp\www\ztest\application\modules\admin\controllers\IndexController.php
Here is the code of Login.php
class Admin_Model_Form_Login extends Zend_Form
{
public function init()
{
parent::init();
$this->setAction('/admin/index/login')->setMethod('post');
$account = new Zend_Form_Element_Text('account');
$account->setLabel('Username')->setRequired(true);
$account->setOrder(1);
$this->addElement($account);
$password = new Zend_Form_Element_Password('password');
$password->setLabel('Password');
$password->setOrder(2);
$this->addElement($password);
$submit = new Zend_Form_Element_Submit('login');
$submit->setLabel('Login');
$submit->setOrder(3);
$this->addElement($submit);
}
}
Have you added a Bootstrap.php file to your module's path?
The file should be found in /application/modules/admin/Bootstrap.php
Similar to this:
class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{
//Can be left blank
}

Fatal error: Class 'Form_BugReport' not found

I've been working through the Apress book 'Pro Zend Framework Techniques'. I've hit a point where I am trying to render the form on a view.
The form is called BugReport, which is located at forms/BugReportForm.php; here is the contents of the file:
<?php
class Form_BugReportForm extends Zend_Form
{
public function init()
{
// add element: author textbox
$author = this->createElement('text', 'author');
$author->setLabel('Enter your name:');
$author->setRequired(TRUE);
$author->setAttrib('size', 30);
$this->addElement($author);
// add element: email textbox
$email = $this->createElement('text', 'email');
$email->setLabel('Your email address:');
$email->setRequired(TRUE);
$email->addValidator(new Zend_Validate_EmailAddress());
$email->addFilters(array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower()
));
$email = setAttrib('size', 40);
$this->addElement($email);
// add element: date textbox
$date = $this->createElement('text', 'date');
$date->setLabel('Date the issue occurred (dd-mm-yyyy)');
$date->setRequired(TRUE);
$date->addValidator(new Zend_Validate_Date('MM-DD-YYYY'));
$date->setAttrib('size', 20);
$this->addElement($date);
// add element: URL textbox
$url = $this->createElement('text', 'url');
$url->setLabel('Issue URL:');
$url->setRequired(TRUE);
$url->setAttrib('size', 50);
$this->addElement($url);
// add element: description text area
$description = $this->createElement('textarea', 'description');
$description->setLabel('Issue description:');
$description->setRequired(TRUE);
$description->setAttrib('cols', 50);
$description->setAttrib('rows', 4);
$this->addElement($description);
// add element: priority select box
$priority = $this->createElement('select', 'priority');
$priority->setLabel('Issue priority:');
$priority->setRequired(TRUE);
$priority->addMultiOptions(array(
'low' => 'Low',
'med' => 'Medium',
'high' => 'High'
));
$this->addElement($priority);
// add element: status select box
$status = $this->createElement('select', 'status');
$status->setLabel('Current status:');
$status->setRequired(TRUE);
$status->addMultiOptions(array(
'new' => 'New',
'in_progress' => 'In Progress',
'resolved' => 'Resolved'
));
$this->addElement($status);
// add element: submit button
$this->addElement('submit', 'submit', array('label' => 'Submit'));
}
}
This form in controlled via the BugController controller located at /controllers/BugController.php
<?php
class BugController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function createAction()
{
// action body
}
public function submitAction()
{
$frmBugReport = new Form_BugReport();
$frmBugReport->setAction('/bug/submit');
$frmBugReport->setMethod('post');
$this->view->form = $frmBugReport();
}
}
And finally I have the following autoloaders in my bootstrap.
protected function _initAutoload()
{
// Add autoloader empty namespace
$autoLoader = Zend_Loader_Autoloader::getInstance();
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
'resourceTypes' => array(
'form' => array(
'path' => 'forms/',
'namespace' => 'Form_',
)
),
));
// Return it so it can be stored by the bootstrap
return $autoLoader;
}
The error I am getting can be seen here: http://zend.danielgroves.net/bug/submit
Or, if you'd rather just read it: Fatal error: Class 'Form_BugReport' not found in /home/www-data/zend.danielgroves.net/htdocs/application/controllers/BugController.php on line 23
Any ideas on what I've done wrong, and so how this can be fixed?
Edit
ArneRie pointed out I was using the wrong class name, but unfortunately this hasn't fixed the issue. Here's how BugController looks now:
<?php
class BugController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function createAction()
{
// action body
}
public function submitAction()
{
$frmBugReport = new Form_BugReportForm();
$frmBugReport->setAction('/bug/submit');
$frmBugReport->setMethod('post');
$this->view->form = $frmBugReport;
}
}
Although this did get rid of the error in question, a new one has taken it's place.
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /home/www-data/zend.danielgroves.net/htdocs/application/forms/BugReportForm.php on line 8
Line 8 is interestingly /* Initialize action controller here */
You have a small typo. The bug is in your form. You are missing a $ before the "this" on line 9. Good luck with the rest of your project, it is a very good book for starters but there are a few small errors in it. Check the editors web site for details:http://www.apress.com/9781430218791/ in the errata section.
<?php
class Form_BugReportForm extends Zend_Form
{
public function init()
{
// add element: author textbox
//Next line is the line to change (add a $ before the "this")
$author = $this->createElement('text', 'author');
$author->setLabel('Enter your name:');
$author->setRequired(TRUE);
$author->setAttrib('size', 30);
$this->addElement($author);
Try it with: $frmBugReport = new Form_BugReportForm();
You're using the wrong class name.

Zend Framework - How does a controller point to a model?

This is a problem that I cannot figure out after hours of googling, the Zend Framework documentation didn't explain what i needed to know.
I have a file: /application/controllers/RegisterController.php
class RegisterController extends Zend_Controller_Action
{
}
How do I point this file to use classes from: /application/models/User.php
class Application_Model_User
{
}
The code works great when the file is named Register.php
What configurations do i need to make to point a controller to a specific model?
In your bootstrap, you can start by declaring your namespace:
protected function _initAutoload() {
//Autoloader
$autoLoader = Zend_Loader_Autoloader::getInstance();
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
'resourceTypes' => array(
//Tells the application where to find the models
'model' => array(
'path' => 'models/',
'namespace' => 'Model_'
)
)
));
return $autoLoader;
}
Your model: /application/models/User.php
class Model_User extends Zend_Db_Table_Abstract
{
}
Then in you controller: /application/controllers/RegisterController.php
class RegisterController extends Zend_Controller_Action
{
public function indexAction() {
$model = new Model_User();
}
}