multiple file upload symfony 2 - symfony

How to use multiple files upload in symfony? I'm not really
sure how to do it 'the symfony way'. I read How to handle File Uploads with Doctrine, but how upload many files?
I try use collection field type and add setFiles method to object model
public function setFiles($files)
{
$this->files = $files;
foreach ($files as $file) {
$file->setObject($this);
}
}
but have exception (this always worked for normal model without any files)
Fatal error: Call to undefined method
Symfony\Component\HttpFoundation\File\UploadedFile::setObject()
please help me.
UPDATED:
I use for main object second form with file, and...
$files = $this->getRequest()->files->get('val_image');
foreach($files as $file){
$foto = new Foto;
$foto->setFile($file);
$foto->setPremises($premises->getPremises());
$this->getEm()->persist($foto);
}
it's works :)

Maybe this plugin can help you:
https://github.com/caoimhin/Symfony-jQuery-File-Upload/blob/master/Resources/public/README.md

Related

How to upload multiple media files "image or video" for RESTFull API in Laravel 5.7?

I'm working on RESTFul API Project in Larave 5.7, and I'm using postman to test my APIs, I'm trying to upload multiple images or videos but nothing work with me!
I tried this way, however, it never gets inside the foreach loop!
And I also tried to use allFiles instead of file but it gives me only one file (maybe the last selected one)!!
foreach ($files as $file) {
$extension = $file->getClientOriginalExtension();
$check = in_array($extension,$allowedfileExtension);
if($check) {
foreach($request->fileName as $mediaFiles) {
// save here
}
} else {
return response()->json(['invalid_file_format'], 422);
}
return response()->json(['file_uploaded'], 200);
}
I was uploading the files in a wrong way with Postman!
This is the correct way :D
It's worked :D

Extbase: Command Controller is not getting Registered

I am new to Extbase. There are two xml files that I want to access. One is abc.dll?type=xml from which I select the ID and then use this Id to fetch the values of other XML file(xyzzy.dll?type=xml and save all the data to the db. I want to create a task in Extbase and run it from command line.
Below is my code:
ext_localconf.php
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers'][] = 'TYPO3\Example\Command\XMLFetcherCommandController';
XMLFetcherCommandController:
namespace TYPO3\Example\Command;
class XMLFetcherCommandController extends \TYPO3\CMS\Extbase\Mvc\Controller\CommandController{
/**
* xmlload
*
* #return void
*/
public function findCommand(){
$path="http://abc.dll?type=room&content=xml";
$readXML=file_get_contents($path);
$xml = simplexml_load_string($readXML, "SimpleXMLElement",LIBXML_NOCDATA); $objectManager=\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$classesRepository = $objectManager->get('TYPO3\\Example\\Domain\\Repository\\ClassesRepository');
$json=json_encode($xml);
$xmlArray=json_decode($json,true);
$serialized_array = serialize($xmlArray);
$unserialized_array = unserialize($serialized_array);
$rooms = $unserialized_array['Rooms']['Room'];
foreach($rooms as $room){
$fetchXML= \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\Example\\Domain\\Model\\Classes');
$fetchXML->setRoomKey($room['Key']);
$fetchXML->setRoomID($room['ID']);
$classesRepository->add($fetchXML);
$newpaths[]='http:/xyz.dll?content=xml&type=room&id='.$room['ID'];
foreach($newpaths as $newpath){
$readLessons=file_get_contents($newpath);
$xmlLessons= simplexml_load_string($readLessons, "SimpleXMLElement",LIBXML_NOCDATA);
$objectManager=\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$classesRepository = $objectManager->get('Example\\Example\\Domain\\Repository\\ClassesRepository');
$json=json_encode($xml);
$xmlArray=json_decode($json,true);
$serialized_array = serialize($xmlArray);
$unserialized_array = unserialize($serialized_array);
$Lessons = $unserialized_array['Lesson'];
foreach ($Lessons as $Lesson) {
$fetchXMLNew= \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Example\\Example\\Domain\\Model\\Classes');
$date=date('Ymd',strtotime($Lesson['Date']));
$start=date('Hi',strtotime($Lesson['Start']));
$finish=date('Hi',strtotime($Lesson['Finish']));
$startdatetime=date('YmdHi',strtotime("$date$start"));
$finishdatetime=date('YmdHi',strtotime("$date$finish"));
$fetchXMLNew->setStartdatetime($startdatetime);
$fetchXMLNew->setEnddatetime($finishdatetime);
$classesRepository->add($fetchXML);
}
}
}
$classesRepository->persistAll();
}
}
}
?>
When I run- php cli_dispatch.phpsh extbase help - from cmd, I could not see my command controller which means it is not registered properly. Could you suggest if this is the right way to do it? At First, I created a Service and tried to call it, but since there was a lot of data it was taking a lot of time.
Maybe it does not work, becouse your class can not be loaded with autoloader?
If a class is not available, it will not be registerd.
(#see CommandManager->getAvailableCommands !class_exists($className)).
I think you need to escape the back slashes (=> Double Slashes)
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers'][]
= 'TYPO3\\Example\\Command\\XMLFetcherCommandController';
If this not work, you can also check the Namespace of your class. Why does it start with "TYPO3"?
If this also not work, you can try load your class hardcoded with require_once in AdditionalConfiguration.php to figure out whats wrong

mvc 5 read and display text file content

I am trying to read a text file and display it on plage. This is what I did. But I am getting error
The process cannot access the file
'D:\wwwroot\TestProject\Logs\TestLog.log' because it is being used by
another process.
Controller Code
Array LogFileData = null;
var logFileNameWithPath = Server.MapPath("D:\wwwroot\TestProject\Logs\TestLog.log");
if (System.IO.File.Exists(logFileNameWithPath))
{
LogFileData = System.IO.File.ReadAllLines(logFileNameWithPath);
}
ViewBag.logFileContent = LogFileData;
View Code
#if (ViewBag.logFileContent != null)
{
foreach (string dataLine in ViewBag.logFileContent)
{
#dataLine
<br />
}
}
The log file is created and used by a service. My code works when I stop service. But I am not trying to write to file exclusively at the same time service is writing to it. Infact I am trying to read at a time when service is not writing to it. Any advice on how can I fix this? THanks.
Generally, you need to specify the "access mode" when you try to read the file. Please take a look here. Try to open the file into a FileStream with appropriate access.
I will post some code when I can.

Localization in ASP.NET MVC 4 using App_GlobalResources

I am trying to accomplish two things:
Localize the “built-in” error messages for “FieldMustBeDate” and "FieldMustBeNumeric".
Localize some of the other error messages you would encounter, for example, "PropertyValueRequired".
By using http://forums.asp.net/t/1862672.aspx/1 for problem 1 and MVC 4 ignores DefaultModelBinder.ResourceClassKey for problem 2 I have managed to get both working locally.
However as soon as I publish to a website, the “built-in” error messages defaults back to English while the other error messages stay localized.
I have read several places that using the App_GlobalResources should be avoided, however I am unable to accomplish problem 1 without using this.
I have created a .resx file with the name “WebResources.resx”, set the Build Action to “Embedded”, set the Copy to Output Directory to “Do no Copy”, set the Custom Tool to “PublicResXFileCodeGenerator” and set the Custom Tool Namespace to “Resources”.
The Project itself is set to only Publish files that are needed.
My Global.asax.cs contains the following (relevant) code:
ClientDataTypeModelValidatorProvider.ResourceClassKey = "WebResources";
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(RequiredAttribute),
typeof(MyRequiredAttributeAdapter));
And the class MyRequiredAttributeAdapter contains the following code:
public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
public MyRequiredAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
RequiredAttribute attribute
)
: base(metadata, context, attribute)
{
if (attribute.ErrorMessageResourceType == null)
{
attribute.ErrorMessageResourceType = typeof(Resources.WebResources);
}
if (attribute.ErrorMessageResourceName == null)
{
attribute.ErrorMessageResourceName = "PropertyValueRequired";
}
}
}
This is working locally however does anyone have any idea on how to get the "built in" messages to work after this is published?
Thank you for your help!
Best regards,
Andreas
I figured this one out myself. If you are trying to accomplish the above you must separate the localized error messages.
Create a *.resx file for the other error messages fx "PropertyValueRequired" and set the Build Action to “Embedded”, set the Copy to Output Directory to “Do no Copy”, set the Custom Tool to “PublicResXFileCodeGenerator” and set the Custom Tool Namespace to “Resources”.
In my case I have moved "PropertyValueRequired" to a file called LocalDanish.resx (still in the App_GlobalResources folder) and changed the line in my "MyRequiredAttributeAdapter" from
attribute.ErrorMessageResourceType = typeof(Resources.WebResources);
to
attribute.ErrorMessageResourceType = typeof(Resources.LocalDanish);
In order to get the "built in" error messages to work, you must create two *.resx files. I have created WebResources.resx and WebResources.da.resx. Do NOT change anything, leave the settings on them on default (Build Action to "Content", etc.). I guess the website automatically looks for the *.da.resx files in my case because I have set the globalization in my WebConfig:
<globalization uiCulture="da-DK" culture="da-DK"/>
Hope this helps anybody.
Best regards,
Andreas
I have made some minor additions to the original post, which didn't translate all messages in my case.
(String length and invalid property values)
Follow the above steps, to create the *.resx files, set their properties, and then set the locale in web.config, as described by Andreas.
Then create a couple of adapters:
// As described in original post:
public class LocalizedRequiredAttributeAdapter : RequiredAttributeAdapter
{
public LocalizedRequiredAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
RequiredAttribute attribute
)
: base(metadata, context, attribute)
{
if (attribute.ErrorMessageResourceType == null)
attribute.ErrorMessageResourceType = typeof(Resources.Resources);
if (attribute.ErrorMessageResourceName == null)
attribute.ErrorMessageResourceName = "PropertyValueRequired";
}
}
// Addition to original post:
public class LocalizedStringLengthAttributeAdapter : StringLengthAttributeAdapter
{
public LocalizedStringLengthAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
StringLengthAttribute attribute
)
: base(metadata, context, attribute)
{
if (attribute.ErrorMessageResourceType == null)
attribute.ErrorMessageResourceType = typeof(Resources.Resources);
if (attribute.ErrorMessageResourceName == null)
attribute.ErrorMessageResourceName = "StringLengthAttribute_ValidationError";
}
}
And in Global.asax.cx:
// Addition to original post: (Used for "PropertyValueInvalid")
DefaultModelBinder.ResourceClassKey = "Resources";
// As described in original post:
ClientDataTypeModelValidatorProvider.ResourceClassKey = "Resources";
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(LocalizedRequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(LocalizedStringLengthAttributeAdapter));

Phpunit testing with ZF2 Album Module fails while connecting to AlbumTable

I am trying the phpunit in the Zf2 album module by following the online ZF2 tutorial. Below is the debug information.
Album\Model\AlbumTableTest::testFetchAllReturnsAllAlbums
Argument 1 passed to Album\Model\AlbumTable::__construct() must be an instance of Zend\Db\Adapter\Adapter, instance of Mock_TableGateway_fb3537df given, called in D:\www\zend2\tests\module\Album\src\Album\Model\AlbumTableTest.php on line 26 and defined
And the function used is
public function testFetchAllReturnsAllAlbums()
{
$resultSet = new ResultSet();
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway',
array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with()
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
$this->assertSame($resultSet, $albumTable->fetchAll());
}
And the 26th line mentioned in the debug information is
$albumTable = new AlbumTable($mockTableGateway);
Which calls to the following functon in Album\Model\AlbumTable::__construct()
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new Album());
$this->initialize();
}
Any help to over come this failed test is much appreciated.
Got it solved. I happened to see that the Album module given in the Zend Framework2 tutorial has been changed. I followed it once again to correct the changed codes. Now the mentioned issue has been sorted out.

Resources