Zend - inputfilter get randomize name - zend-form

Hello I'm trying ZF2 form with an input file.
I have a form with a file input and I want to insert the randomize name into my db.
How I can return the randomized name?
thanks.
This is the simple form class:
class OrdineForm extends Formhttp://stackoverflow.com/questions/ask
public function __construct($name = null)
{
parent::__construct('ordine');
$this->setAttribute('method', 'post');
$this->addElements();
$this->addInputFilter();
}
public function addElements(){
$this->add(array(
'name' => 'pdf',
'attributes' => array(
'type' => 'text',
'disabled' =>'true',
),
'options' => array(
'label' => 'PDF',
),
));
// FILE INPUT
$file = new File('file');
$file
->setLabel('PDF attach')
->setAttributes(array(
'id' => 'file',
));
$this->add($file);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Add',
'id' => 'submitbutton',
'class' => 'btn btn-success'
),
));
}
public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
$fileInput= new FileInput('file');
$fileInput->setRequired(false);
$fileInput->getFilterChain()->attachByName(
'filerenameupload',
array(
'target' => './public/tmpuploads/',
'randomize' => true,
"UseUploadname" => true,
)
);
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
}

After you have validated the form in your controller you can use $form->getData();
there should be a key 'file' as that is what you named your file element. Within that a key 'tmp_name'.
This will be the randomized name.
Eg:
public function uploadfileAction()
{
//get form and filter
$form = $this->getServiceLocator()->get('SomeModule\Form\UploadFileForm');
$filter = $this->getServiceLocator()->get('SomeModule\Form\UploadFileFilter');
$form->setInputFilter($filter->getInputFilter());
if ($this->getRequest()->isPost()) {
//merge files with post
$post = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
//set data in form
$form->setData($post);
//check is valid- form data will now contain new name
if ($form->isValid()) {
var_dump($form->getData());
}
}
}
The resulting array dump may look something like this:
array(13) {
["file"]=>
array(5) {
["name"]=>
string(14) "some-pdf.pdf"
["type"]=>
string(24) "application/pdf"
["tmp_name"]=>
string(46) "/public/tmpuploads/new-randomized-name.pdf"
["error"]=>
int(0)
["size"]=>
int(651264)
}
["submit"]=>
string(6) "Submit"
["csrf"]=>
string(32) "4df771bb2fb14e28992a408583745946"
}
You can then just do:
$formData = $form->getData();
$fileNewLocation = $formData['file']['tmp_name'];
//do what you want with $fileNewLocation

Related

How to use the InputFilter in a nested mapper model class in Zend Framework 2?

Everyone, who started ZF2 learning with the "Get started" tutorial, will know the model class Album (s. below).
Now I want to extend my model with songs. One album can have 0 or more songs. The songs will get a new talbe songs (id, title, album_id) and the mapper Album\Model\Song. The mapper Album\Model\Song will be built similar to Album\Model\Album. The mapper Album\Model\Album will get a new property songCollection (array of Album\Model\Song objects or maybe something like Album\Model\SongCollection object).
Does it make sence to use the InputFilter for "nested" (mapper) classes?
How should the getInputFilter() be modified?
How should the setInputFilter() be modified? OK, now it is not implemented at all. But it's approximately clear how to do it for a shallow class structure -- and not clear how to implement it for a mapper, that references another mapper(-s).
Album\Model\Album
<?php
namespace Album\Model;
use Zend\Stdlib\ArraySerializableInterface;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Album implements InputFilterAwareInterface, ArraySerializableInterface {
public $id;
public $artist;
public $title;
protected $inputFilter;
public function exchangeArray(array $data) {
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->artist = (isset($data['artist'])) ? $data['artist'] : null;
$this->title = (isset($data['title'])) ? $data['title'] : null;
}
public function toArray() {
return $this->getArrayCopy();
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception('Not used');
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int')
)
)));
$inputFilter->add($factory->createInput(array(
'name' => 'artist',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim')
),
'validarots' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100
)
)
)
)));
$inputFilter->add($factory->createInput(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim')
),
'validarots' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100
)
)
)
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
I think you are a little confused with the relationship with the models and mappers set out in this example.
The 'mappers' would be the TableGateway objects, such as AlbumTable, SongTable etc. The Album and Song classes yo would call models, or Domain Objects, these are what represent the actual entities in your application. The Mappers just take care of persisting them in your database etc.
When using the TableGateway implementation, I would let each Domain Object (such as Ablum) handle the InputFilter for the attributes it's TableGateway is going to persist (such as AlbumTable).
For the example you stated, I would not change the Album Models InputFilter at all. The reason is the relationship with Songs is this:
Album HAS many songs, Song Belongs to Album (the Song would have the link back to the Album)
Add a new Song Object and Gateway:
<?php
namespace Album\Model;
use Zend\Stdlib\ArraySerializableInterface;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Song implements InputFilterAwareInterface, ArraySerializableInterface {
protected $id;
protected $album;
protected $title;
protected $inputFilter;
// Added Getters / Setters for the attributes rather than
// having public scope ...
public function setAlbum(Album $album)
{
$this->album = $album;
}
public function getAlbum()
{
return $this->album;
}
public function exchangeArray(array $data) {
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->title = (isset($data['title'])) ? $data['title'] : null;
if(isset($data['album_id'])) {
$album = new Album();
$album->exchangeArray($data['album_id']);
$this->setAlbum($album);
}
}
public function toArray() {
return $this->getArrayCopy();
}
public function getArrayCopy() {
return array(
'id' => $this->id,
'album_id' => $this->getAlbum()->id,
'title' => $this->title,
);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception('Not used');
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int')
)
)));
$inputFilter->add($factory->createInput(array(
'name' => 'album_id',
'required' => true,
'filters' => array(
array('name' => 'Int')
)
)));
$inputFilter->add($factory->createInput(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim')
),
'validarots' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100
)
)
)
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
Notice no need to change the Album Model as the relationship is 'Song Belongs to Album'.
When you object relationships get more complex you will want to look at using Hydrators to build the objects for you (http://framework.zend.com/manual/2.0/en/modules/zend.stdlib.hydrator.html)
Now you would create a SongTable to persist this new Object for you:
<?php
namespace Album\Model;
use Zend\Db\TableGateway\TableGateway;
class SongTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getSong($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveSong(Song $song)
{
$data = array(
'album_id' => $song->getAlbum()->id,
'title' => $song->title,
);
$id = (int)$song->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getSong($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function fetchAlbumSongs(Album $album)
{
$resultSet = $this->tableGateway->select(array(
'album_id' => $album->id
));
return $resultSet;
}
public function addSongsToAlbum(Album $album)
{
foreach($this->fetchAlbumSongs($album) as $song) {
$album->addSong($song);
}
}
}
You Could then Modify you Album model to allow Songs to be added:
class Album implements InputFilterAwareInterface, ArraySerializableInterface {
// Other stuff here
/**
* #var array
*/
protected $songs = array();
public function addSong(Song $song)
{
$this->songs[] = $song;
}
public function getSongs()
{
return $this->songs;
}
}
You can then build your object graph easily, I would usually make a server to do do this kind of thing:
AlbumService.php
public function getAlumbWithSongs(int $id)
{
$album = $this->getAlbumTable()->getAlbum($id);
if($album) {
$this->getSongTable()->addSongsToAlbum($album);
}
return $album;
}

Yii select2 - returned data cannot be selected

I have been looking into select2 and yii and have managed to load data via json request/response.
The issue I'm faced with is when I try to select an entry of the returned data, I can not.
Where am I going wrong ? The data returnd by the action is json formatted as CustomerCode and Name
Widget code in form
$this->widget('bootstrap.widgets.TbSelect2', array(
'asDropDownList' => false,
'name' => 'CustomerCode',
'options' => array(
'placeholder' => 'Type a Customer Code',
'minimumInputLength' => '2',
'width' => '40%',
'ajax' => array(
//'url'=> 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
'url'=> Yii::app()->getBaseUrl(true).'/customer/SearchCustomer',
'dataType' => 'jsonp',
'data' => 'js: function (term,page) {
return {
term: term, // Add all the query string elements here seperated by ,
page_limit: 10,
};
}',
'results' => 'js: function (data,page) {return {results: data};}',
),
'formatResult' => 'js:function(data){
var markup = data.CustomerCode + " - ";
markup += data.Name;
return markup;
}',
'formatSelection' => 'js: function(data) {
return data.CustomerCode;
}',
)));
code snipped from controller action SearchCustomer
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderJSON(Customer::model()->searchByCustomer($term));
renderJSON function from base controller class
protected function renderJSON($data)
{
header('Content-type: application/json');
echo $_GET['callback'] . "(";
echo CJSON::encode($data);
echo ")";
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
Appreciate any help on this
i try.
change
'dataType' => 'jsonp' to 'dataType' => 'json'
and check json format
https://github.com/ivaynberg/select2/issues/920

Yii CForm, Nested Forms Ajax Validation

I have created the following nested forms array;
return array(
'elements' => array(
'contact' => array(
'type' => 'form',
'elements' => array(
'first_name' => array(
'type' => 'text',
),
'last_name' => array(
'type' => 'text',
)
),
),
'lead' => array(
'type' => 'form',
'elements' => array(
'primary_skills' => array(
'type' => 'textarea',
),
),
),
),
'buttons' => array(
'save-lead' => array(
'type' => 'submit',
'label' => 'Create',
'class' => 'btn'
),
)
);
i have view page like this
echo $form->renderBegin();
echo $form['lead'];
echo $form['contact'];
echo $form->buttons['save-lead'];
echo $form->renderEnd();
my actionCreate is like this
$form = new CForm('application.views.leads.register');
$form['lead']->model = new Lead;
$form['contact']->model = new Contact;
// how can i perform ajax validation only for $form['contact']
$this->performAjaxValidation($model);
//if contact form save btn is clicked
if ($form->submitted('save-lead') && $form['contact']->validate() &&
$form['lead']->validate()
) {
$contact = $form['contact']->model;
$lead = $form['lead']->model;
if ($contact->save()) {
$lead->contact_id = $contact->id;
if ($lead->save()) {
$this->redirect(array('leads/view', 'id' => $lead->id));
}
}
}
ajax validation method is
protected function performAjaxValidation($model)
{
if (isset($_POST['ajax']) && $_POST['ajax'] === 'contact') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
so my question is how can i perform ajax validation on $form['contact'] and $form['lead'] elements individually?
You can have several forms in a page but they should not be nested.
Nested forms are invalid.
You should make your own validation
in actionCreate and actionUpdate of your controller you must add (i have main model "Invoice" and secondary "InvoiceDetails", and there could be more than 1 form for InvoiceDetails). But of course forms cannot be nested!
public function actionCreate()
{
...
$PostVar = 'Invoices';
if (Yii::app()->request->isAjaxRequest)
{ // if ajax
$this->performAjaxValidation($model, strtolower($PostVar) . '-form');
$PostVar = ucfirst($PostVar);
if (isset($_POST[$PostVar]))
{
$model->attributes = $_POST[$PostVar];
$dynamicModel = new InvoiceDetails(); //your model
$valid = self::validate($model, $dynamicModel);
if (!isset($_POST['ajax']))
{
if (isset($_POST['InvoiceDetails']))
{
$allDetails = array();
$allDynamicModels = $_POST['InvoiceDetails'];
//your own customization
foreach ($allDynamicModels as $key => $value)
{
$InvDet = InvoiceDetails::model()->findByPk($_POST['InvoiceDetails'][$key]['id']);
if (!isset($InvDet))
{
$InvDet = new InvoiceDetails();
}
$InvDet->attributes = $_POST['InvoiceDetails'][$key];
$InvDet->save();
$allDetails[] = $InvDet;
}
}
$model->invoicedetails = $allDetails;
if ($model->save())
{
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
}
else
{
echo CJSON::encode(array('status' => 'error saving'));
Yii::app()->end();
}
}
// Here we say if valid
if (!isset($valid))
{
echo CJSON::encode(array('status' => 'success'));
}
else
{
echo $valid;
}
Yii::app()->end();
}
else
{
$this->renderPartial('_form', ...);
}
}
else
{
// not AJAX request
$this->render('_form', ...));
}
Nested Forms are invalid. You can use scenarios to validate the form at different instances.
Example:
`if ($form->submitted('save-lead'){
$form->scenario = 'save-lead';
if($form->validate()) {
$form->save();
}
} else {
$form->scenario = 'contact';
if($form->validate()){
$form->save();
}
}
$this->render('_form', array('form'=>$form);`

Invalid type given. String expected - Zend Framework 2

Im working on Zend Framework 2 especially with Zend Forms. I have declared a Select dropdown box in
Form:
$selectElement = new Element\Select('selectElement');
$selectElement->setAttribute('title', 'Select a Value')
->setAttribute('id', 'id');
$data = array(
array(
//Fetching the values from database
),
);
$selectElement->setAttribute('multiple', 'multiple')
->setValueOptions($data);
$this->add($selectElement);
InputFilter:
$inputFilter->add($factory->createInput(array(
'name' => 'selectElement',
'required' => false,
'filters' => array(
array(
'name' => 'Int'
),
),
)));
I have used Zend Debug to get the values which are in the selectElement dropbox in this fashion:
$dataSelectElements = $this->getRequest()->getPost('selectElement');
\Zend\Debug\Debug::dump($dataSelectElements);
Debug Result:
array(4) {
[0] => string(2) "20"
[1] => string(2) "22"
[2] => string(2) "23"
[3] => string(2) "75"
}
Basically Im getting the id's from the selectElement form to store it in the database. Right now Im getting a notice and zend form error:
Notice Error:
Notice: Array to string conversion in ..\zendframework\zendframework\library\Zend\Filter\Int.php on line 29
And a form invalid error:
array(1) {
[0] => array(1) {
["selectElement "] => array(1) {
["explodeInvalid"] => string(35) "Invalid type given. String expected"
}
}
}
Is there a solution to over come this problem. Any help would be appreciated.
The Int filter will attempt to make an Integer out of your array of data, which is not going to work.
Previously I've used the Callback filter, which can be used to loop through the data and check if each value is an Int.
For example:
'filters' => array(
array(
'name' => 'Callback',
'options' => array(
'callback' => function($values) {
return array_filter($values, function($value) {
return ((int)$value == $value);
});
}
)
),
),
I did bit differently, something like this
form
class Companyform extends Form
{
public function __construct()
{
// we want to ignore the name passed
parent::__construct('company');
$this->setAttribute ('method', 'post');
$this->setAttribute ('class', 'form-horizontal');
$this->add ( array (
'name' => 'parentID',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'id' => 'parentID',
'type' => 'select',
'placeholder' => "Parent Company",
),
'options' => array(
'label' => 'Parent Company'
)
));
$this->add(array(
'name' => 'btnsubmit',
'attributes' => array(
'id' => 'btnsubmit',
'type' => 'submit',
'value' => 'Add',
'class' => 'btn btn-primary'
),
));
}
}
controller
public function addAction()
{
$request = $this->getRequest();
$companyList = $this->_getCompanyList();
$form = new Companyform();
$form->get('parentID')->setAttribute('options',$companyList);
if ($request->isPost())
{
$company = new Company();
$form->setInputFilter($company->getInputFilter());
$form->setData($request->getPost());
if ($form->isvalid())
{
}
}
}
public function _getCompanyList()
{
$companies = $this->Em()->getEntityManager()->getRepository('XXXX\Entity\Company')->findBy(array('isDeleted'=>'0'));
$companyIDList = array();
$companyIDList[0] = "No Parent";
foreach ($companies as $company)
{
$companyIDList[$company->id] = $company->companyName;
}
return $companyIDList;
}
Entity class
protected $inputFilter;
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'companyName',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 255,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
You may need to add following library in entity
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
In ZendFramework 2, when you creating a (add) element from your Form file, Check the attribute: inarrayvalidator is true.
$this->add(array(
'name' => 'select_name',
'type' => 'select',
'id' => 'select_name',
'options' => array(
'label' => 'Select Name',
),
'attributes' => array(
'id' => 'select_id',
'inarrayvalidator' => true,
),
));
I hope, this works...

dynamically adding text boxes in drupal form api

I want to have a add more button on clicking which i can add dynamically, textboxes in a drupal form api.. can someone help on this?
Thanks in advance
Take a look at Adding dynamic form elements using AHAH. It is a good guide to learn AHAH with Drupal's form API.
EDIT: For an example, install the Examples for Developers module, it has an AHAH example you can use to help you learn.
Here is an example how to solve this with Ajax in Drupal 7(If anyone want I can convert it also to Drupal 6 using AHAH(name before it became Ajax)).
<?php
function text_boxes_form($form, &$form_state)
{
$number = 0;
$addTextbox = false;
$form['text_lists'] = array
(
'#tree' => true,
'#theme' => 'my_list_theme',
'#prefix' => '<div id="wrapper">',
'#suffix' => '</div>',
);
if (array_key_exists('triggering_element', $form_state) &&
array_key_exists('#name', $form_state['triggering_element']) &&
$form_state['triggering_element']['#name'] == 'Add'
) {
$addTextbox = true;
}
if (array_key_exists('values', $form_state) && array_key_exists('text_lists', $form_state['values']))
{
foreach ($form_state['values']['text_lists'] as $element) {
$form['text_lists'][$number]['text'] = array(
'#type' => 'textfield',
);
$number++;
}
}
if ($addTextbox) {
$form['text_lists'][$number]['text'] = array(
'#type' => 'textfield',
);
}
$form['add_button'] = array(
'#type' => 'button',
'#name' => 'Add',
'#ajax' => array(
'callback' => 'ajax_add_textbox_callback',
'wrapper' => 'wrapper',
'method' => 'replace',
'effect' => 'fade',
),
'#value' => t('Add'),
);
return $form;
}
function ajax_add_textbox_callback($form, $form_state)
{
return $form['text_lists'];
}
function text_boxes_menu()
{
$items = array();
$items['text_boxes'] = array(
'title' => 'Text Boxes',
'description' => 'Text Boxes',
'page callback' => 'drupal_get_form',
'page arguments' => array('text_boxes_form'),
'access callback' => array(TRUE),
'type' => MENU_CALLBACK,
);
return $items;
}