how to use "filerenameupload" filter in zend framework2? - forms

i add file element in form class with:
$this->add(array(
'type' => 'Zend\Form\Element\File',
'name' => 'logo_file',
'options' => array(
'label' => 'Select your logo image file:',
),
));
then add filter in model for filtering form data. i use "filerenameupload" filter to upload selected file :
$inputFilter = new InputFilter();
$inputFilter->add($factory->createInput(array(
'name' => 'logo_file',
'required' => false,
'filters' => array(
array('name' => 'filerenameupload',
'options'=>array(
//'target' => "./data/logo.png",
'randomize' => true,
)
),
),
)));
and in controller i call setInputFilter, setData and isValid normally. other elements go filter good, but "logo_file" does not be saved in "./data/logo.png".
in fact "filter" function in "Zend\Filter\File\RenameUpload" class does not be executed.
i use this link :
zf2 File Uploding Toturial
Someone's trying to solve this problem?

Have you tried using the full name for the Filter?
array(
'name' => 'Zend\Filter\File\RenameUpload'
)
You also need to make sure you add both the files array and the POST data to the form when validating, example:
$postArr = $request->getPost()->toArray();
$fileArr = $this->params()->fromFiles('logo_file');
$formData = array_merge(
$postArr, // $_POST
array('logo_file' => $fileArr['name']) // $_FILE...
);
$importForm->setData($formData);

Try:
Form.php:
public function addElements(){
$this->add(array(
'name' => 'image',
'attributes' => array(
'type' => 'file',
),
'options' => array(
),
));
FormValidator.php
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
"name" => "image",
"required" => true,
"filters" => array(
array("name" => "StripTags"),
array("name" => "StringTrim"),
array(
"name" => "Zend\Filter\File\RenameUpload",
"options" => array(
"target" => '/home/limonazzo/UPLOADDIR<----------',
"randomize" => true,
"use_upload_name" => true,
"use_upload_extension" => true
)
)
),
"validators" => array(
array(
"name" => "Zend\Validator\File\IsImage",
"break_chain_on_failure" => true,
"options" => array(
),
),
array(
"name" => "Zend\Validator\File\Extension",
"break_chain_on_failure" => true,
"options" => array(
"extension" => "jpg,jpeg,png",
),
),
array(
"name" => "Zend\Validator\File\Size",
"break_chain_on_failure" => true,
"options" => array(
"min" => "1kB",
"max" => "1024kB",
),
),
array(
"name" => "Zend\Validator\File\ImageSize",
"break_chain_on_failure" => true,
"options" => array(
"minWidth" => 10,
"minHeight" => 10,
"maxWidth" => 250,
"maxHeight" => 350,
),
),
),
)));
In controlle.php
$form = new Form();
$formValidator = new FormValidator();
$form->setInputFilter($formValidator->getInputFilter(''));
if ($form->isValid()) {
$data = $form->getData(\Zend\Form\FormInterface::VALUES_AS_ARRAY);
$imgName = $data["image"]["tmp_name"];

Related

How can I hide create new button in TYPO3 TCA type inline?

I would like to hide "create new" image button in case of TCA for field type is inline.
My code is below:
<pre>
'image' => array(
'label' => 'Image',
'config' => array(
'type' => 'inline',
'foreign_table' => 'sys_file_reference',
'foreign_field' => 'uid_foreign',
'foreign_sortby' => 'sorting_foreign',
'foreign_table_field' => 'tablenames',
'foreign_match_fields' => array(
'fieldname' => 'field_slide_image',
),
'foreign_label' => 'uid_local',
'foreign_selector' => 'uid_local',
'foreign_selector_fieldTcaOverride' => array(
'config' => array(
'appearance' => array(
'elementBrowserType' => 'file',
'elementBrowserAllowed' => $allowedFileExtensions
)
)
),
'filter' => array(
array(
'userFunc' => 'TYPO3\\CMS\\Core\\Resource\\Filter\\FileExtensionFilter->filterInlineChildren',
'parameters' => array(
'allowedFileExtensions' => $allowedFileExtensions,
'disallowedFileExtensions' => $disallowedFileExtensions
)
)
),
'appearance' => array(
'useSortable' => TRUE,
'headerThumbnail' => array(
'field' => 'uid_local',
'width' => '45',
'height' => '45c',
),
'showPossibleLocalizationRecords' => FALSE,
'showRemovedLocalizationRecords' => FALSE,
'showSynchronizationLink' => FALSE,
'showAllLocalizationLink' => FALSE,
'showPossibleRecordsSelector' => "hide",
'enabledControls' => array(
'info' => FALSE,
'new' => false,
'dragdrop' => TRUE,
'sort' => true,
'hide' => TRUE,
'delete' => TRUE,
'localize' => TRUE,
),
),
'behaviour' => array(
'localizationMode' => 'select',
'localizeChildrenAtParentLocalization' => TRUE,
),
),
)
</pre>
I have added this code 'new' => false, but still it is not working.
Found Solution :
I have found one solution https://forge.typo3.org/issues/71918
I hope this can help for other users.
Use the permission system of TYPO3 to only allow read access to the field for a certain user group.
Hide "New" Button in TCA with
['appearance']['enabledControls']['new'] = false
This works in 8.x only.
Found Solution :
I have found one solution https://forge.typo3.org/issues/71918
// Render the level links (create new record):
if ($config['appearance']['enabledControls']['new']) {
> $levelLinks = $this->getLevelInteractionLink('newRecord', $nameObject . '-' . $foreign_table, $config);
}
Afaik, the "new" button only becomes hidden if the "maxitems" limit is set and reached.

How to put a picture instead of text in radio element in ZF2?

Subject: How to put a picture instead of text in radio element in ZF2?
code:
Options field:
array(
'spec' => array(
'type' => 'radio',
'name' => 'fcaptcha',
'options' => array(
'label' => 'Капча',
'label_attributes' => array(
'class' => 'control-label',
),
),
'attributes' => array(
'required' => 'required',
),
),
)
Controller:
$temp[0] = 'Here you need to put a picture instead of text';
$temp[1] = 'Here you need to put a picture instead of text';
$form->get('fcaptcha')->setValueOptions($temp);
You can do that just with some CSS. Here's a simple example that you can adapt for your purpose :
Let say you have this Zend\Form\Element\Radio element :
array(
'type' => 'Zend\Form\Element\Radio',
'name' => 'fcaptcha',
'options' => array(
'value_options' => array(
'0' => 'something1',
'1' => 'something2',
),
),
'attributes' => array(
'id'=>"fcaptcha-id"
)
)
CSS :
radio-option1 {background-image:url(option1.png);}
radio-option2 {background-image:url(option2.png);}
Some JS :
$(document).ready(function(){
$(':radio[value="0"]').addClass('radio-option1');
$(':radio[value="1"]').addClass('radio-option2');
});

zend_form isValid always false

I write code for a site that uses Zend 1.
I want to rewrite the old admin interface in zend, but my form fails to validate.
I'll post the form, the validation code and the debug output here.
Form:
class Form_Admin_Address_Neu extends Zend_Form {
public function init() {
$this->setMethod('post');
$this->addElement('text', '_street', array(
'label' => 'Strasse:',
'size' => 60,
'required' => true,
'filters' => array('StringTrim'),
));
$this->addElement('text', '_zip', array(
'label' => 'PLZ:',
'size' => 6,
'required' => true,
'filters' => array('StringTrim'),
));
$this->addElement('text', '_city', array(
'label' => 'Stadt:',
'required' => true,
'size' => 30,
'filters' => array('StringTrim'),
));
$this->addElement('text', '_lat', array(
'label' => 'Latitude:',
'required' => true,
'size' => 30,
'validators' => array('Float'),
'filters' => array('Stringtrim'),
));
$this->addElement('text', '_lng', array(
'label' => 'Longitude:',
'required' => true,
'size' => 30,
'validators' => array('Float'),
'filters' => array('Stringtrim'),
));
$this->addElement('checkbox', '_hidden', array(
'label' => 'Hidden:',
'size' => 1,
'filters' => array('Int', 'Null'),
));
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Senden',
));
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
$this->setAction('/admin/address/list');
}
}
additional fields (i just post 1 here, 2nd is like it):
class Form_Admin_Elements_CountrySelect extends Zend_Form_Element_Select {
public function init() {
$countrymapper = new Mapper_Country();
$this->addMultiOption(0, 'Please select...');
foreach ($countrymapper->fetchAll() as $country) {
$this->addMultiOption($country->getId(), $country->getName());
}
$this->setLabel("Land:");
}
}
Code:
$addForm = new Form_Admin_Address_Neu();
$regionselect = new Form_Admin_Elements_RegionSelect('region_id');
$regionselect->setRequired(true);
$addForm->addElement($regionselect);
$countryselect = new Form_Admin_Elements_CountrySelect('country_id');
$countryselect->setRequired(true);
$addForm->addElement($countryselect);
if ($addForm->isValid($_POST)) {
...
} else {
print_r($_POST);
print_r($addForm->getErrorMessages());
print_r($addForm->getCustomMessages());
print_r($addForm->getErrors());
}
output:
Array
(
[_street] => sdvdsvsv
[_zip] => 111111
[_city] => sdfgsf
[_lat] => 1.0
[_lng] => 2.1
[_hidden] => 0
[country_id] => 1
[region_id] => 3
[submit] => Senden
[csrf] => d18dfed9d26e28d7a52aa4983b00667e
)
Array
(
)
Array
(
)
Array
(
[_street] => Array
(
)
[_zip] => Array
(
)
[_city] => Array
(
)
[_lat] => Array
(
[0] => notFloat
)
[_lng] => Array
(
[0] => notFloat
)
[_hidden] => Array
(
)
[submit] => Array
(
)
[csrf] => Array
(
)
[region_id] => Array
(
)
[country_id] => Array
(
)
)
As I see it, the validation fails, but i dont know why.
The values are present in the $_POST, but the form doesnt validate.
i even tried with isValidPartial(), but same result.
I think i'm doing something fundamentally wrong.
A hint would be great.
ty in advance
Try to enter a comma instead of a point in Latitude and Longitude.
1,0 and 2,1 instead of 1.0 and 2.1
I think it's a problem about Locale of your validator

How to set a variable in ObjectSelect criteria params in DoctrineModule

I'd like to know how to set a variable in ObjectSelect criteria params.
My code is as follow:
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'shop',
'attributes' => array(
'class' => 'chosen-select form-control'
),
'options' => array(
'object_manager' => $this->objectManager,
'target_class' => '\Godana\Entity\Shop',
'property' => 'name',
'label' => 'Shop',
'label_attributes' => array(
'class' => 'col-sm-3 control-label',
),
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('owner' => $this->shopOwner),
),
),
),
)
);
and it returns empty value but if I use a static value like 'criteria' => array('owner' => 1) it returns data from my db.
shouldn't it be $this->shopOwner->getId() ?

Zend_Dojo_Form passwordTextBox validator don't work

I am a newbie in zf, recently I m making a register form using zend_dojo_form and there are two passwordtextbox elements, which u know, one is for entering password and the other is to confirm the former one, then I using the validator 'token' but failed, here is part of my code.
$this->addElement('PasswordTextBox','password',array(
'label'=>'password:',
'required'=>true,
'trim'=>true,
'regExp'=>'^[a-z0-9]{6,18}$',
'invalidMessage'=>'password should be 6-18',
'Decorators' => array(
'DijitElement',
'Errors',
array(array('data'=>'HtmlTag'),array('tag'=>'td','align'=>'left')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr','align'=>'right'))
)
)
);
//$this->addElement($password1);
$this->addElement('PasswordTextBox','password2',array(
'label'=>'confirm password:',
'required'=>true,
'trim'=>true,
//'regExp'=>'^[a-z0-9]{6,18}$',
'validators'=>array(array('identical',false,array('token'=>'password'))),
'invalidMessage'=>'the password you enter not the same',
'Decorators' => array(
'DijitElement',
'Errors',
array(array('data'=>'HtmlTag'),array('tag'=>'td','align'=>'left')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr','align'=>'right'))
)
)
);
Here's a sample that should be functional:
class Application_Form_Register extends Zend_Dojo_Form {
public function init() {
$this
->setOptions(array('name' => 'registerForm'))
// username
->addElement('TextBox', 'first_name', array(
'filters' => array('StringTrim', 'StringToLower'),
'id' => 'name_register',
'required' => true,
'label' => 'Fornavn(e):',
))
->addElement('TextBox', 'last_name', array(
'filters' => array('StringTrim', 'StringToLower'),
'id' => 'surname_register',
'label' => 'Efternavn:',
))
->addElement('ValidationTextBox', 'email', array(
'filters' => array('StringTrim', 'StringToLower'),
'validators' => array(
'EmailAddress',
array('StringLength', false, array(3, 60)),
),
'regExp' => "^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$",
'id' => 'email_register',
'required' => true,
'label' => 'E-mail:',
))
//password
->addElement('PasswordTextBox', 'password', array(
'filters' => array('StringTrim'),
'validators' => array(
'Alnum',
array('StringLength', false, array(6, 20)),
),
'regExp' => "^([a-zA-Z0-9_\-!-=]){4,32}$",
'tooltipPosition' => 'above',
'invalidMessage' => 'Krav til password: mellem 4 og 32 i længde og kun karakterer som tal, bogstaver eller blandt [ _-!"#%&/()=] er tilladt',
'id' => 'password_register',
'onKeyDown' => 'arguments[0].keyCode == dojo.keys.ENTER && application.submitRegistration(dijit.byId(\'registerForm\'));',
'required' => true,
'label' => 'Password:',
))
->addElement('PasswordTextBox', 'password_confirm', array(
'filters' => array('StringTrim'),
'validators' => array(
'Alnum',
array('StringLength', false, array(6, 20)),
),
'id' => 'passwordconfirm_register1',
'onKeyDown' => 'arguments[0].keyCode == dojo.keys.ENTER && application.submitRegistration(dijit.byId(\'registerForm\'));',
'required' => true,
'label' => 'Gentag password:',
))
->addElement('PasswordTextBox', 'password_confirm', array(
'filters' => array('StringTrim'),
'validators' => array(
'Alnum',
array('StringLength', false, array(6, 20)),
),
'id' => 'passwordconfirm_register2',
'onKeyDown' => 'arguments[0].keyCode == dojo.keys.ENTER && application.submitRegistration(dijit.byId(\'registerForm\'));',
'required' => true,
'label' => 'Gentag password:',
))
->addElement('Hidden', 'action', array(
'id' => 'action_register',
'value' => 'register',
))
->addElement('Button', 'foo', array(
'id' => 'foo_register',
'onClick' => 'application.submitRegistration(dijit.byId(\'registerForm\'))',
'label' => 'Register'
)
);
$this->_decorate();
}
// renders nulled empty labels and adds classnames, related to element name
protected function _decorate() {
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'div', 'class' => 'zend_form_contents')),
'DijitForm'
));
foreach ($this->getElements() as $el) {
$el->addDecorator('HtmlTag', array('tag' => 'div', 'class' => $el->getName() . '-wrap'));
if ($el->helper == 'Button')
continue;
else if (strlen(trim($el->getLabel())) == 0)
$el->addDecorator('Label', array('tag' => null));
else
$el->addDecorator('Label', array('tag' => 'div', 'class' => $el->getName() . '-label'));
}
}
}
Focusing on the two password fields - in terms of what makes clientside validation tick, lets filter out the Zend_Form_Element attributes:
->addElement('PasswordTextBox', 'password_2_', array(
// strictly serverside, only accepts alphanumerical pwds lengths 6 through 20
'validators' => array(
'Alnum',
array('StringLength', false, array(6, 20)),
),
// widget id
'id' => 'passwordconfirm_register1',
// both client-/server-side - triggers 'emptyMessage' validation
'required' => true,
// runs with the form.validate() and events onblur, oninit, onkeypress
// if ! dijit.get("value").match(dijit.regExp) show 'invalidMessage'
// this example matches the serverside reqs
'regExp' => "^([a-zA-Z0-9_\-!-=]){6,32}$",
// shown with form.validate(), dijit.validate() and input.blur() if regExp is not a match against value
'invalidMessage' => 'Password musts: 6 to 32 chars and only numbers, letters or amongst [ _-!"#%&/()=]',
))
And a second pwd field, same attributes but with a different validator
->addElement('PasswordTextBox', 'password_2_', array(
// strictly serverside, only accepts alphanumerical pwds lengths 6 through 20
'validators' => array(
array('identical',false,array('token'=>'password'))
),
// widget id
'id' => 'passwordconfirm_register2',
'required' => true,
// in theory, we would define 'validator' in programmatic construct of
// the validationtextbox. but this will not work with the way Zend handles dojo
// 'validator' => 'function(value, constraints) { return "BAD PRACTICE" }'
));
// add javascript code to run onload and to extend the 'register2' properly
$this->getElement()
->getView()
->headScript()
->appendFile($baseUrl . '/js/Validator.js');
By now, only 'required' is validated clientside in the passwordconfirm_register2 widget. Lets fix in what markup factory does in regards to 'bad practice' in the above lines. Remove that line and add the javascript code instead, containing:
// file: baseUrl/js/Validator.js
dojo.addOnLoad(function() {
dijit.byId('passwordconfirm_register2').validate = function(value, constraints) {
if(dijit.byId('passwordconfirm_register1').get("value") != value) {
this.invalidMessage = "Passwords are not identical";
return false;
}
return true
});
});