问题
I can't get fileprg plugin to work with the files in a collection.
I am trying to upload multiple files using FormCollections, but in $form->getData() there is no key related to my collection or the files .
I tested the form and fileprg with simple file input (in the same form) and it worked uploaded/renamed and it was in the $form->getData().
what am i missing ? is there anything special to be done with the collections to get it to work ?
回答1:
In the file \Zend\Mvc\Controller\Plugin\FilePostRedirectGet the two functions you want to look at are getNonEmptyUploadData (that is supplying a callback function) and traverseInputs (which is a glorified foreach that checks each input filter then runs it and the value through the above callback).
To allow this plugin to work on collections you will need to extend the class and alter the above functions:
/**
* Traverse the InputFilter and run a callback against each Input and associated value
*
* @param InputFilterInterface $inputFilter
* @param array $values
* @param callable $callback
* @return array|null
*/
protected function traverseInputs(InputFilterInterface $inputFilter, $values, $callback)
{
$returnValues = null;
foreach ($values as $name => $value) {
if (!$inputFilter->has($name)) {
continue;
}
$input = $inputFilter->get($name);
if ($input instanceof InputFilterInterface && is_array($value)) {
if ($input instanceof CollectionInputFilter) {
$retVal = null;
foreach ($value as $k => $val) {
$retVal2 = $this->traverseInputs($input->getInputFilter(), $val, $callback);
if ($retVal2)
$retVal[$k] = $retVal2;
}
} else
$retVal = $this->traverseInputs($input, $value, $callback);
if (null !== $retVal) {
$returnValues[$name] = $retVal;
}
continue;
}
$retVal = $callback($input, $value);
if (null !== $retVal) {
$returnValues[$name] = $retVal;
}
}
return $returnValues;
}
/**
* Traverse the InputFilter and only return the data of FileInputs that have an upload
*
* @param InputFilterInterface $inputFilter
* @param array $data
* @return array
*/
protected function getNonEmptyUploadData(InputFilterInterface $inputFilter, $data)
{
return $this->traverseInputs(
$inputFilter,
$data,
function ($input, $value) {
$messages = $input->getMessages();
if (is_array($value) && $input instanceof FileInput && empty($messages)) {
$rawValue = $value;
if (
(isset($rawValue['error']) && $rawValue['error'] !== UPLOAD_ERR_NO_FILE)
|| (isset($rawValue[0]['error']) && $rawValue[0]['error'] !== UPLOAD_ERR_NO_FILE)
) {
return $value;
}
}
return;
}
);
}
Here is a diff that shows what lines were altered: https://github.com/rafam31/zf2/commit/c481e7404faf93beb4c67a6a4b7490fec15d279b
来源:https://stackoverflow.com/questions/16521888/zf2-fileprg-with-files-in-collection