Laravel 5.7 variable being lowercased in HTML <option> tag - naming-conventions

I'm trying to make a ternary operation in my option tag. But when I call the variable, it becomes to lowercase and laravel could not find it.
Here is my code:
<select name="media_type" id="media_type" class="">
<option value="">Select an option</option>
<option value="image" {{ $campBanner->media_type == 'image' ? 'selected' : '' }}>Image</option>
<option value="video" {{ $campBanner->media_type == 'video' ? 'selected' : '' }}>Video</option>
</select>
And here is the result of the laravel's exception:
<select name="media_type" id="media_type" class="">
<option value="">Select an option</option>
<option value="image" <?php echo e($campbanner->media_type == 'image' ? 'selected' : ''); ?>>Image</option>
<option value="video" <?php echo e($campbanner->media_type == 'video' ? 'selected' : ''); ?>>Video</option>
</select>
ErrorException (E_ERROR)
Undefined variable: campbanner
Is it a bug? Or I just messed up something?
UPDATE
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CampBanner;
use App\Http\Requests\StoreCampBanner;
class CampBannerController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('CampBanner.index', [
'campBanner' => CampBanner::all()
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('CampBanner.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(StoreCampBanner $request)
{
CampBanner::create(
$request->validated()
);
return ['message' => 'Banner Camp baru telah ditambahkan'];
}
/**
* Display the specified resource.
*
* #param \App\CampBanner $campBanner
* #return \Illuminate\Http\Response
*/
public function show(CampBanner $campBanner)
{
return view('CampBanner.show', compact('campBanner'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\CampBanner $campBanner
* #return \Illuminate\Http\Response
*/
public function edit(CampBanner $campBanner)
{
return view('CampBanner.edit', compact('campBanner'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\CampBanner $campBanner
* #return \Illuminate\Http\Response
*/
public function update(StoreCampBanner $request, CampBanner $campBanner)
{
$campBanner->fill(
$request->validated()
)->save();
return ['message' => 'Camp Banner berhasil diperbarui'];
}
/**
* Remove the specified resource from storage.
*
* #param \App\CampBanner $campBanner
* #return \Illuminate\Http\Response
*/
public function destroy(CampBanner $campBanner)
{
$campBanner->delete();
return ['message' => 'Camp Banner berhasil dihapus.'];
}
}

Put your controller codes for better help ..

Related

Call to a member function update() on null in laravel 9

What is wrong with this function? I ve got error on this line:
$bookShelf->update($request->all());
My Controller
<?php
namespace App\Http\Controllers;
use App\Models\BookShelf;
use App\Models\Book;
use App\Models\Category;
use App\Http\Requests\StoreBookShelfRequest;
use App\Http\Requests\UpdateBookShelfRequest;
class BookShelfController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$bookshelves = BookShelf::with('book')->latest()->get();
// $bookshelves = BookShelf::all();
$model = new BookShelf();
$books = Book::with('category')->latest()->get();
// $books = Book::all();
$categories = Category::with(['users.books.shelf']);
return view('admin.bookshelves.index', compact('bookshelves', 'books', 'model', 'categories'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$model = new BookShelf;
$categories = Category::all();
$books = Book::with('category')->latest()->get();
return view('admin.bookshelves.create', compact('categories', 'model', 'books'));
}
/**
* Store a newly created resource in storage.
*
* #param \App\Http\Requests\StoreBookShelfRequest $request
* #return \Illuminate\Http\Response
*/
public function store(StoreBookShelfRequest $request)
{
BookShelf::create($request->all());
return redirect('admin_area/shelves')->with('success', 'Selamat Data Berhasil Ditambahkan');
}
/**
* Display the specified resource.
*
* #param \App\Models\BookShelf $bookShelf
* #return \Illuminate\Http\Response
*/
public function show(BookShelf $bookShelf)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\BookShelf $bookShelf
* #return \Illuminate\Http\Response
*/
public function edit($shelf_code)
{
$model = BookShelf::find($shelf_code);
$categories = Category::all();
$books = Book::with('category')->latest()->get();
return view('admin.bookshelves.edit', compact('categories', 'model', 'books'));
}
/**
* Update the specified resource in storage.
*
* #param \App\Http\Requests\UpdateBookShelfRequest $request
* #param \App\Models\BookShelf $bookShelf
* #return \Illuminate\Http\Response
*/
public function update(UpdateBookShelfRequest $request, BookShelf $bookShelf)
{
$bookShelf = BookShelf::find($bookShelf->shelfcode);
$bookShelf->update($request->all());
return redirect('admin_area/bookshelves')->with('success', 'Selamat Data Berhasil Di Ubah');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\BookShelf $bookShelf
* #return \Illuminate\Http\Response
*/
public function destroy(BookShelf $bookShelf, $id)
{
$bookShelf = BookShelf::find($id);
$bookShelf->delete();
return redirect('admin_area/shelves')->with('success', "Data berhasil disimpan");
}
}
My Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BookShelf extends Model
{
use HasFactory;
protected $guarded = ['id'];
protected $load = ['category', 'book'];
public function category()
{
return $this->belongsTo(Category::class);
}
public function book()
{
return $this->belongsTo(Book::class);
}
public function getRouteKeyName()
{
return 'shelfcode';
}
}
My Edit View
#extends('layouts.main')
#section('title', 'Edit Data Buku')
#section('content')
<div class="container">
<div class="row mt-3 d-flex justify-content-center">
<div class="col-md-9 justify-content-center">
<div class="card card-primary card-outline">
<div class="card-header">
<h5 class="m-0">Edit Data Rak Buku</h5>
</div>
<div class="card-body">
<h6 class="card-title"></h6>
<form method="POST" action="{{ route('shelves.update', $model->shelfcode) }}"
enctype="multipart/form-data">
#csrf
{{-- <input type="hidden" name="_method" value="PATCH"> --}}
#method('PUT')
#include('admin.bookshelves.form')
<div class="form-group">
<button class="btn btn-warning btn-sm glyphicon glyphicon-save">
<span class="fas fa-edit"> Edit Data Buku</span>
</button>
</div>
</form>
{{-- #endsection --}}
</div>
</div>
</div>
</div>
</div>
#endsection
Looks like you're querying your BookShelf model by the wrong key. You can also remove $bookShelf = BookShelf::find($bookShelf->shelfcode); from the update function since it is already injected by the framework when you use model binding (https://laravel.com/docs/9.x/routing#route-model-binding).
When you have this common error, there is no trap, it litteraly means that you are trying to call update on null.
It's exactly like doing null->update($request->all()) (and you can try, you'll have the same error).
The only explanation here is that $bookShelf = BookShelf::find($bookShelf->shelfcode); returns null.
Regarding the structure itself,
public function update(UpdateBookShelfRequest $request, BookShelf $bookShelf)
{
$bookShelf = BookShelf::find($bookShelf->shelfcode);
//...
}
makes no sense since the whole purpose of using implicit route binding is to avoid the manual query you are making to retrieve $bookShelf. It should already be the BookShelf you need.

Synfony 3 + Vich upload bundle - Failed to set metadata before uploading the file

My problem is to retrieve metadata before uploading the file.
My config file:
vich_uploader:
db_driver: orm
mappings:
media:
uri_prefix: /uploads/
upload_destination: '%kernel.root_dir%/../web/uploads'
inject_on_load: false
delete_on_update: true
delete_on_remove: true
I have an entity MEDIA :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
**
* #ORM\Entity
* #Vich\Uploadable
*/
class Media
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #Vich\UploadableField(mapping="media", fileNameProperty="fileName",originalName="originalFileName")
*
* #var File
*/
private $file;
/**
* #ORM\Column(type="string", length=50)
*/
private $fileName;
/**
* #ORM\Column(type="string", length=255, nullable=false)
*/
private $originalFileName;
/**
* #ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $file
*
* #return Media
*/
public function setFile(File $file = null)
{
$this->file = $file;
if ($file) {
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
/**
* #return File|null
*/
public function getFile()
{
return $this->file;
}
/**
* #param string $fileName
*
* #return Media
*/
public function setFileName($fileName)
{
$this->fileName = $fileName;
return $this;
}
/**
* #return string|null
*/
public function getFileName()
{
return $this->fileName;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
*
* #return Media
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set originalFileName
*
* #param string $originalFileName
*
* #return Media
*/
public function setOriginalFileName($originalFileName)
{
$this->originalFileName = $originalFileName;
return $this;
}
/**
* Get originalFileName
*
* #return string
*/
public function getOriginalFileName()
{
return $this->originalFileName;
}
}
And here is my controller:
/**
* Creates a new media entity.
*
* #Route("/new", name="media_new")
* #Method({"GET", "POST"})
*
* #param Request $request
*
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function newAction(Request $request)
{
$media = new Media();
$form = $this->createForm(MediaType::class, $media);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($media);
$em->flush();
return $this->redirectToRoute(
'media_list'
);
}
return $this->render(
'media/new.html.twig',
[
'media' => $media,
'form' => $form->createView(),
]
);
}
And my form:
<?php
/**
* Created by PhpStorm.
* User: rafael
* Date: 4/10/17
* Time: 12:46 PM
*/
namespace AppBundle\Form;
use AppBundle\Entity\Media;
use AppBundle\Entity\MediaDescriptionHelper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class MediaType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class)
->add('save', SubmitType::class, [
'attr' => ['class' => 'btn-primary btn-block']
]);
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['data_class' => Media::class]);
}
}
The problem is with the mapping of these values :
#Vich\UploadableField(mapping="media", fileNameProperty="fileName",originalName="originalFileName")
When I submit my form these values are 'null' :
An exception occurred while executing 'INSERT INTO media (file_name, original_file_name, updated_at) VALUES (?, ?, ?)' with params ["get_image_resultat_sans_cache2.php.jpeg", null, "2017-04-12 10:11:56"]:
I have these issues with all parameters :
(https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/usage.md)
The UploadableField annotation has a few options. They are as follows:
mapping: required, the mapping name specified in the bundle configuration to use;
fileNameProperty: required, the property that will contain the name of the uploaded file;
size: the property that will contain the size in bytes of the uploaded file;
mimeType: the property that will contain the mime type of the uploaded file;
originalName: the property that will contain the origilal name of the uploaded file.
I don't see what I did wrong...
Here is my Media (entity) after the form is submitted :
Media {#403 ▼
-id: null
-file: UploadedFile {#15 ▼
-test: false
-originalName: "get_image_resultat_sans_cache2.php.jpeg"
-mimeType: "image/jpeg"
-size: 203751
-error: 0
path: "/tmp"
filename: "php9xsTdF"
basename: "php9xsTdF"
pathname: "/tmp/php9xsTdF"
extension: ""
realPath: "/tmp/php9xsTdF"
aTime: 2017-04-12 10:11:56
mTime: 2017-04-12 10:11:56
cTime: 2017-04-12 10:11:56
inode: 6160452
size: 203751
perms: 0100600
owner: 1000
group: 1000
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
-fileName: null
-originalFileName: null
It seems that's a problem when set metadata before uploading the file...
Thanks a lot in advance...
Which version of VichUploaderBundle do you use?
The documentation for the annotations refers to the dev-master one, while the stable one (1.5.3) doesn't support annotation for metadata out of the box.
You can see that Vich\UploaderBundle\Mapping\Annotation\UploadableField.php in the 1.5.3 version handles only annotations 'mapping' and 'fileNameProperty'.
While in the dev-master, it handles those and size, mimeType and originalName.
Same thing with Vich\UploaderBundle\Metadata\Driver\AnnotationDriver
If you want to achieve this in the 1.5.3 version you need to create an eventListener.
Here are the event triggered by Vich : https://github.com/dustin10/VichUploaderBundle/blob/1.5.3/Event/Events.php

LiipImagineBundle Picture does not appear after filtering

I'm using the VichUploadBundle to upload images into my database, and would like to have the thumbnails of the images displayed on the website with LiipImage.
This is my config.yml with the files set up
//.....
vich_uploader:
db_driver: orm
twig: true
mappings:
product_image:
uri_prefix: /images/products
upload_destination: '%kernel.root_dir%/../web/images/products'
inject_on_load: false
delete_on_update: true
delete_on_remove: true
liip_imagine:
# configure resolvers
resolvers:
# setup the default resolver
default:
# use the default web path
web_path: ~
# your filter sets are defined here
filter_sets:
# use the default cache configuration
cache: ~
# the name of the "filter set"
my_thumb:
# adjust the image quality to 75%
quality: 75
# list of transformations to apply (the "filters")
filters:
# create a thumbnail: set size to 120x90 and use the "outbound" mode
# to crop the image when the size ratio of the input differs
thumbnail: { size: [120, 90], mode: outbound }
# create a 2px black border: center the thumbnail on a black background
# 4px larger to create a 2px border around the final image
background: { size: [124, 98], position: center, color: '#000000' }
Most of the code for liip is copied straight up from the documentation for testing.
This is my routing.yml
app:
resource: "#AppBundle/Controller/"
type: annotation
_liip_imagine:
resource: "#LiipImagineBundle/Resources/config/routing.xml
Finally I have the Image entity I want to upload.
It's as well a code copied from the official Vich documentation
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity
* #Vich\Uploadable
*/
class Image
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// ..... other fields
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
*
* #var File
*/
protected $imageFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
protected $imageName;
/**
* #ORM\Column(type="string", length=100)
*
* #var string
*/
protected $imageTitle = null;
/**
* #ORM\Column(type="string", length=100)
*
* #var string
*/
protected $imageAuthor = null;
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*
* #return Product
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
/**
* #return File|null
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* #param string $imageName
*
* #return Product
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* #return string|null
*/
public function getImageName()
{
return $this->imageName;
}
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
protected $updatedAt;
/**
* #return null
*/
public function getImageTitle()
{
return $this->imageTitle;
}
/**
* #param null $imageTitle
*/
public function setImageTitle($imageTitle)
{
$this->imageTitle = $imageTitle;
}
/**
* #return null
*/
public function getImageAuthor()
{
return $this->imageAuthor;
}
/**
* #param null $imageAuthor
*/
public function setImageAuthor($imageAuthor)
{
$this->imageAuthor = $imageAuthor;
}
}
In my controller I have the image table put into array with $em
$em = $this->getDoctrine()->getManager();
$list = $em->getRepository(Image::class)->findAll();
Which I later put into the view and (would want to) print them like so:
{% for l in list %}
<tr>
<td>
<img src="{{ asset('/images/products/'~l.imageName) | imagine_filter('my_thumb') }}" alt="{{ l.imageName }}">
</td>
<td>{{ l.imageTitle }}</td>
<td>{{ l.imageAuthor }}</td>
</tr>
{% endfor %}
Unfortunately the output looks like this:
Now the path is fine. The image works well without the imagine_filter(). Same effect would occur when using the Vich Assets.
When checked the path the image is linked under is:
http://localhost:8000/media/cache/resolve/my_thumb/images/products/hqdefault.jpg
The path to images is
web/images/products
Is there anyone who know what might be the issue?
Or to provide an alternative bundle for creating image thumbnails
All help would be amazing
FIXED: Enabling GD and filenames in php.ini and restating apache, afterwards clearing the cache fixed everything

A choice list based on database values in sonata

is it possible to add a choice list in configureformfields with choices values mapped from the database instead of configuring it manually like this :
->add('testfield', 'choice', array('choices' => array(
'1' => 'choice 1',
'2' => 'choice 2',)))
if the entity is correctly mapped then you can just use:
->add('testfield')
and Sonata admin will do the job.
Let's say you have a Product class linked to a Category class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Product
*
* #ORM\Table(name="product")
*
*/
class Product
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
*/
protected $category;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set category
*
* #param Category $category
*
* #return Product
*/
public function setCategory(Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return Category
*/
public function getCategory()
{
return $this->category;
}
}
Simply using:
->add('category')
will provide a select form field with all the categories.
You can also use SONATA_TYPE_MODEL if you want something more advanced:
<?php
// src/AppBundle/Admin/ProductAdmin.php
class ProductAdmin extends AbstractAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
$imageFieldOptions = array(); // see available options below
$formMapper
->add('category', 'sonata_type_model', $imageFieldOptions)
;
}
}
The documentation is on this page: Form Types
Hope this helps!

Multiple file upload with Symfony2

I'm trying to upload multiple files via a form, but I can only upload one file at a time, the last one I mark in the browser. Is there a way to upload more images with Symfony2 using a simple form?
Here is the twig template of the form I'm using to be able to mark more than one file:
{{ form_widget(form.post_image, { 'attr': {'multiple': 'multiple' }}) }}
Ok binding issue solved (enctype syntax error) : i'll give you the code i use. maybe it will help...
I have a Gallery Entity
class Gallery
{
protected $id;
protected $name;
protected $description;
private $urlName;
public $files; // the array which will contain the array of Uploadedfiles
// GETTERS & SETTERS ...
public function getFiles() {
return $this->files;
}
public function setFiles(array $files) {
$this->files = $files;
}
public function __construct() {
$files = array();
}
}
I have a form class that generate the form
class Create extends AbstractType {
public function buildForm(FormBuilder $builder, array $options) {
$builder->add('name','text',array(
"label" => "Name",
"required" => TRUE,
));
$builder->add('description','textarea',array(
"label" => "Description",
"required" => FALSE,
));
$builder->add('files','file',array(
"label" => "Fichiers",
"required" => FALSE,
"attr" => array(
"accept" => "image/*",
"multiple" => "multiple",
)
));
}
}
Now in the controller
class GalleryController extends Controller
{
public function createAction() {
$gallery = new Gallery();
$form = $this->createForm(new Create(), $gallery);
// Altering the input field name attribute
$formView = $form->createView();
$formView->getChild('files')->set('full_name', 'create[files][]');
$request = $this->getRequest();
if($request->getMethod() == "POST")
{
$form->bindRequest($request);
// print "<pre>".print_r($gallery->getFiles(),1)."</pre>";
if($form->isValid())
{
// Do what you want with your files
$this->get('gallery_manager')->save($gallery);
return $this->redirect($this->generateUrl("_gallery_overview"));
}
}
return $this->render("GalleryBundle:Admin:create.html.twig", array("form" => $formView));
}
}
Hope this help...
NB: If someone know a better way to alter this f** name attribute, maybe in the FormView class or by declaring a new field type, feel free to show us your method...
No extra classes needed (except the gallery_manger service but the issue you describe happens before...)
I don't really know what's wrong. Check for your template (maybe wrong enctype... or name attr missmatching)
first try to do a single file upload, check the documentation:
file Field Type
How to handle File Uploads with Doctrine
Once it works, you have to edit some lines.
add input file multiple attribute.
append [] at the end of the input file name attribute (mine is
create...[] because my form class name is create, if your is
createType it will be createType...[])
init $files as an array.
Copy/paste your code here.
All the suggestions I've found here are workarounds for the real situation.
In order to be able to have multiple attachments, you should use form collection.
Quote from the documentation:
In this entry, you'll learn how to create a form that embeds a collection of many other forms. This could be useful, for example, if you had a Task class and you wanted to edit/create/remove many Tag objects related to that Task, right inside the same form.
http://symfony.com/doc/2.0/cookbook/form/form_collections.html
Example case: You have a document, which form is specified by DocumentType. The document must have multiple attachments, which you can have by defining AttachmentType form and adding it as a collection to the DocumentType form.
For sf > 2.2 :
In you form type class, add this overrided method :
public function finishView(FormView $view, FormInterface $form, array $options) {
$view->vars['form']->children['files']->vars['full_name'] .= '[]';
}
Note that i try to do the same thing in sf2 using this syntax:
In the controller:
public function stuffAction() {
$form = $this->createFormBuilder()
->add('files','file',array(
"attr" => array(
"accept" => "image/*",
"multiple" => "multiple",
)
))
->getForm();
$formView = $form->createView();
$formView->getChild('files')->set('full_name', 'form[files][]');
// name param (eg 'form[files][]') need to be the generated name followed by []
// try doing this : $formView->getChild('files')->get('full_name') . '[]'
$request = $this->getRequest();
if($request->getMethod() == "POST") {
$form->bindRequest($request);
$data = $form->getData();
$files = $data["files"];
// do stuff with your files
}
}
return $this->render('Bundle:Dir:index.html.twig',array("form" => $formView));
}
$files will be an array of uploaded files...
Calling $form->createView() to alter the name attribute is certainly not the best way / cleanest way to do it but it's the only one i found that keeps the csrf functionality working, because altering the name attribute in a twig template makes it invalid...
Now I still have an issue using a form class which generate the form, I don't know why during the binding of the form data & object attached to the form my array of uploaded files is transformed in array of (file) name ???
use this methode :
$form = $this->createFormBuilder()
->add('attachments','file', array('required' => true,"attr" => array(
"multiple" => "multiple",
)))
->add('save', 'submit', array(
'attr' => array('class' => 'btn btn-primary btn-block btn-lg'),
'label' => 'save'
))
->getForm();
then you add [] to the name of your input via jQuery :
<input id="form_attachments" name="form[attachments]" required="required" multiple="multiple" type="file">
jQuery code :
<script>
$(document).ready(function() {
$('#form_attachments').attr('name',$('#form_attachments').attr('name')+"[]");
});
</script>
Here is easy example to upload multiple files. I have similar problem with upload files.
https://github.com/marekz/example_symfony_multiply_files_example
For symfony 3.*
First: Both form declatartion:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Form\FilesType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
class UserType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('lastName')
->add('files', CollectionType::class,array(
'entry_type' => FilesType::class,
'allow_add' => true,
'by_reference' => false,
))
;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_user';
}
}
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class FilesType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file');
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Files'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_files';
}
}
Now, my entities:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User {
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="lastName", type="string", length=255)
*/
private $lastName;
/**
* #ORM\ManyToMany(targetEntity="Files", cascade={"persist"})
*/
private $files;
function __construct() {
$this->files = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return User
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set lastName
*
* #param string $lastName
*
* #return User
*/
public function setLastName($lastName) {
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName() {
return $this->lastName;
}
/**
* Get files
*
* #return ArrayCollection
*/
function getFiles() {
return $this->files;
}
/**
* Set files
* #param type $files
*/
function setFiles($files) {
$this->files = $files;
}
}
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Files
*
* #ORM\Table(name="files")
* #ORM\Entity(repositoryClass="AppBundle\Repository\FilesRepository")
*/
class Files
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="file", type="string", length=255, unique=true)
* #Assert\NotBlank(message="Please, upload the product brochure as a PDF file.")
* #Assert\File(mimeTypes={ "application/pdf" })
*/
private $file;
/**
*
* #return Files
*/
function getUser() {
return $this->user;
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set file
*
* #param string $file
*
* #return Files
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return string
*/
public function getFile()
{
return $this->file;
}
}
Finaly, Symfony Controller:
/**
* Creates a new user entity.
*
* #Route("/new", name="user_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request) {
$user = new User();
$form = $this->createForm('AppBundle\Form\UserType', $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$attachments = $user->getFiles();
if ($attachments) {
foreach($attachments as $attachment)
{
$file = $attachment->getFile();
var_dump($attachment);
$filename = md5(uniqid()) . '.' .$file->guessExtension();
$file->move(
$this->getParameter('upload_path'), $filename
);
var_dump($filename);
$attachment->setFile($filename);
}
}
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('user_show', array('id' => $user->getId()));
}
return $this->render('user/new.html.twig', array(
'user' => $user,
'form' => $form->createView(),
));
}
You need to alter the input file name attribute which need to map an array.
<input type="file" name="name[]" multiple />
Methods getChild and set() were removed in 2.3.
Instead of this you should use children[] and vars properties
before:
$formView->getChild('files')->set('full_name', 'form[files][]');
after:
$formView->children['files']->vars = array_replace($formView->children['files']->vars, array('full_name', 'form[files][]'));
Symfony introduced 'multiple' option to file field type in symfony 2.5
$builder->add('file', 'file', array('multiple' => TRUE));
What would happen if there would be some validation errors? Will Symfony Form repost multiple file upload field. Because I tried it and I think for this purpose you need to use collection of file fields. Than symfony form must render all fields have added before correctly.