Zend Form Custom Filter Class not found - zend-framework

My Custom Zend Form Filter Classes are not being loaded.
The Custom Filter Class name is: SF_Filter_AlnumDashes and it resides into:
library/SF/Filter/AlnumDashes.php.
I have configured autoloading for the "SF_" namespace into application.ini:
autoloadernamespaces[] = "SF_"
But when I try to load the Class during Zend Form creation I get error that the class coudn't be found:
Fatal error: Class 'AlnumDashesUnderscore' not found in...
Here is the code that is causing the error in the Zend Form class:
class Admin_Form_Product_Generalinfo extends SF_Form_Abstract {
public function init() {
//set ID Attribute on the form element
$this->setAttrib('id', 'product_general_info');
$elementPrefixPaths = array(
array(
array(
'prefix' => 'SF_Filter',
'path' => 'SF/Filter/', // 'application/validators' in your case
'type' => 'filter',
)
)
);
$this->addElementPrefixPaths($elementPrefixPaths);
$this->addElement('text', 'title', array(
'filters' => array('StringTrim', 'StripTags'),
'validators' => array(
array('StringLength', true, array(2, 250)),
),
'required' => true,
'label' => 'Title',
'attribs' => array(
'id' => 'title',
'class' => 'inputbox'
)
));
$this->getElement('title')->addFilter(array(new AlnumDashesUnderscore(), array(1)));
}
I have other classes into "SF_" Namespace that get load successfully, calling them from Controllers with no problem.

The class is defined as SF_Filter_AlnumDashes, but you're trying to create a new instance of AlnumDashesUnderscore. These class names need to match:
$this->getElement('title')->addFilter(array(new SF_Filter_AlnumDashes(), array(1)));

Related

Zend framework 2 form element normalization

I am migrating an application from Zend 1 to Zend 2 and starting to desperate with one issue. The application works with different locales and therefore, I need to store the data in a normalized way in the database. In Zend 1 I used this code:
public function normalizeNumber( $value )
{
// get the locale to change the date format
$this->_locale = Zend_Registry::get('Zend_Locale' );
return Zend_Locale_Format::getNumber($value, array('precision' => 2, 'locale' => $this->_locale));
}
Unfortunately Zend 2 does not has this Zend_Locale_Format::getNumber any more and I was not able to figure out what function did replace it. I have tried with NumberFormat, but I get only localized data not normalized. I need this function to normalize data I receive from a form via POST. Can someone give some advice?
thanks
Just to complete my question. The Form element definition I am using is the following:
namespace Profile\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class Profile Extends Form implements InputFilterProviderInterface
{
protected $model;
public function __construct( $model, $name = 'assignmentprofile')
{
parent::__construct( $name );
$this->setAttribute( 'method', 'post');
$this->model = $model;
...
$this->add( array(
'name' =>'CommutingRate',
'type' =>'Zend\Form\Element\Text',
'options' => array( // list of options to add to the element
'label' => 'Commuting rate to be charged:',
'pattern' => '/[0-9.,]/',
),
'attributes' => array( // Attributes to be passed to the HTML lement
'type' =>'text',
'required' => 'required',
'placeholder' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
...
'CommutingRate' => array(
'required' => true,
'filters' => array(
array( 'name' => 'StripTags', ),
array( 'name' => 'StringTrim'),
array( 'name' => 'NumberFormat', 'options' => array('locale' => 'en_US', 'style' => 'NumberFormatter::DECIMAL', 'type' => 'NumberFormatter::TYPE_DOUBLE',
))
),
'validators' => array(
array( 'name' => 'Float',
'options' => array( 'messages' => array('notFloat' => 'A valid numeric entry is required')),
),
),),
...
);
}
}
As mentioned before, I am able to localized the data and validate it in the localized manner, but i am failing to convert it back to a normalized manner...

ZF2 Form: NumberFormat-filter with localization

hy,
how can I define the NumberFormat-filter for an input in a fieldset which is aware of the current locale? What I want is that numbers like 1000.33 are displayed in the view like this: 1.000,33 (or whatever locale is specified) I have tried it with the InputFilterProviderInterface, but it doesn't has any effect in the view:
<?php
namespace Customer\Form;
use Customer\Entity\OfferDay;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class OfferDayFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($em)
{
parent::__construct('offerDayFieldset');
$this->setHydrator(new DoctrineHydrator($em))
->setObject(new OfferDay());
$this->add(array(
'name' => 'price',
'type' => 'Text',
'options' => array(
'label' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
'price' => array(
'required' => false,
'filters' => array(
array(
'name' => 'NumberFormat',
'options' => array(
'locale' => 'de_DE',
),
),
),
),
);
}
}
In the view I output the input via the formRow()-function.
I also know that you can use the NumberFormat-Filter programmatically like this (l18n Filters - Zend Framework 2):
$filter = new \Zend\I18n\Filter\NumberFormat("de_DE");
echo $filter->filter(1234567.8912346);
// Returns "1.234.567,891"
but I wanna use the array-notation.
Has anybody done something like this or something similar?
ok this seems not as trivial as I thought :) but I got a solution.
first define the filter like this:
public function getInputFilterSpecification()
{
return array(
'price' => array(
'required' => false,
'filters' => array(
array(
'name' => 'NumberFormat',
'options' => array(
'locale' => 'de_DE',
'style' => NumberFormatter::DECIMAL,
'type' => NumberFormatter::TYPE_DOUBLE,
),
),
),
),
);
}
whereas locale is the currently used locale. This formats the numbers into the currect format before saving it to the database.
In the view, you can use the filter view helper to convert the numbers to the right format:
<?php
$this->plugin("numberformat")
->setFormatStyle(NumberFormatter::DECIMAL)
->setFormatType(NumberFormatter::TYPE_DOUBLE)
->setLocale("de_DE");
?>
<p>
<?php
$currentElement = $form->get('price');
$currentElement->setValue($this->numberFormat($currentElement->getValue()));
echo $this->formRow($currentElement);
?>
</p>
Result:
Database: 12.345 ->
View: 12,345 -> Database: 12.345

Prestashop helper form 'file' type

I m working on prestasshop and I created a helper form inside a controller (for back office). My question is how to upload a document by using the type:'file' from the helper form. Here is the code:
public function __construct()
{
$this->context = Context::getContext();
$this->table = 'games';
$this->className = 'Games';
$this->lang = true;
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->bulk_actions = array('delete' => array('text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')));
$this->multishop_context = Shop::CONTEXT_ALL;
$this->fieldImageSettings = array(
'name' => 'image',
'dir' => 'games'
);
$this->fields_list = array(
'id_game' => array(
'title' => $this->l('ID'),
'width' => 25
)
);
$this->identifier = 'id_game';
parent::__construct();
}
public function renderForm()
{
if (!($obj = $this->loadObject(true)))
return;
$games_list = Activity::getGamesList();
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => $this->l('Game'),
'image' => '../img/admin/tab-payment.gif'
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Game:'),
'desc' => $this->l('Choose a Game'),
'name' => 'id_games',
'required' => true,
'options' => array(
'query' => $games_list,
'id' => 'id_game',
'name' => 'name'
)
),
array(
'type' => 'text',
'label' => $this->l('Game Title:'),
'name' => 'name',
'size' => 64,
'required' => true,
'lang' => true,
'hint' => $this->l('Invalid characters:').' <>;=#{}'
),
array(
'type' => 'file',
'label' => $this->l('Photo:'),
'name' => 'uploadedfile',
'id' => 'uploadedfile',
'display_image' => false,
'required' => false,
'desc' => $this->l('Upload your document')
)
)
);
$this->fields_form['submit'] = array(
'title' => $this->l(' Save '),
'class' => 'button'
);
return AdminController::renderForm();
}
Now how can I upload the document?
Do I have to create a column in the table of the db (games table) for storing the file or something related?
Thanks in advance
I assume this AdminController for your model. Now a model obviously can't hold a file in table column. What you can do is hold path to the uploaded file. That's what you can save.
You should look in AdminController class (which you extended). When you submit a form, one of two method are executed:
processAdd()
processUpdate()
Now investigate the flow logic in these methods. Other methods are called from within this methods, such as:
$this->beforeAdd($this->object); -> calls $this->_childValidation();
$this->validateRules();
$this->afterUpdate($object);
As you can see, there these are the methods where you can do you custom stuff. If you look up these functions in AdminController class, the're empty. They are purposely added so people can override them and put their custom logic there.
So, using these functions, you can validate your uploaded file fields (even though it isnt in the model itself), if it validates you can then assign path to the object; and then in beforeAdd method you can actually move the uploaded file to the desired location (because both child validation and default validation has passed).
The way I've done it:
protected function _childValidation()
{
// Check upload errors, file type, writing permissions
// Use $this->errors['file'] if there is an error;
protected function beforeAdd($object)
{
// create filename and filepath
// assign these fields to object;
protected function afterAdd($object)
{
// move the file
If you allow the file field to be updated, you'll need to to these steps for Update methods as well.
you can get uploaded file using $_FILES['uploadedfile'] in both the functions processAdd() and processUpdate(), you can check all the conditions there and before calling $this->object->save(); to save the form data you can write the code to upload the file in the desired location like
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
since you can't save the file in database you need to save only the name of the file or location on the database
Hope that helps

zendframework form2 how to set a value in a hidden form element l

quick question.
i am trying to set a value in a hidden form element. this is what i did below;but its not working.
i am trying to add the value 7 to the hidden form field. i used the value options field. but its not working.
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id',
'options' => array(
'value_options' => array(
'id'=> 7 ,
), ),
));
below is my form page:
namespace Workers\Form\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class JobSortFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager, $id )
{
parent::__construct('JobSort');
$this->setHydrator(new DoctrineHydrator($objectManager, 'Workers\Entity\JobSort'))
->setObject(new JobSort());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id',
'options' => array(
'value_options' => array(
'id'=> 7 ,
), ),
));
Option value_options is used for multivalue elements (MultiCheckbox, Select, etc.), for simple element like Hidden just set the value attribute:
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id',
'attributes' => array(
'value' => 7,
),
));

how to set readonly property in zend form add element

Hi I am new in zend framework.
I want to set ready only property on input box in zend Form.
example as we do in html
<input type ="text" readonly="readonly" />
this is my zend code:
$this->addElement('text', 'name', array(
'label' => '',
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:338px'),
'autocomplete' => 'off',
'decorators'=>Array(
'ViewHelper',
'Errors',
),
help mee
Try this
$this->getElement('text')->setAttrib('readonly', 'readonly');
Try something like this:
$this->addElement('text','text_field',array('attribs' => array('readonly' => 'true')));
In ZF2 you can create a form by extending Zend\Form and then add form element in the constructor. there you can set the attributes as follows.
use Zend\Form\Form;
class MyForm extends Form {
public function __construct() {
$this->add(array(
'name' => 'name',
'type' => 'Text',
'attributes' => array(
'id' => 'name',
'class' => 'form-control',
'readonly' => TRUE,
),
'options' => array(
'label' => 'Name : '
)
));
}
}