While trying to create fake posts on laravel 8, I met with some errors, first it wasn't creating the posts, then I changed the username to nullable and it created it but I keep having;
Attempt to read property "username" on null
So, I went back to my database and I changed it back to none, but I still receive the same error code, I will post my codes now...
index.blade.php
#extends('layouts.app')
#section('content')
<div class="flex justify-center">
<div class="w-8/12 bg-white p-6 rounded-lg">
<form action="{{ route('posts') }}" method="post" class="mb-4">
#csrf
<div class="mb-4">
<label for="body" class="sr-only">Body</label>
<textarea name="body" id="body" cols="30" rows="4" class="by-gray-100 border-2
w-full p-4 rounded lg #error('body') border-red-500 #enderror" placeholder="Post something!"></textarea>
#error('body')
<div class="text-red-500 mt-3 text-sm">
{{$message}}
</div>
#enderror
</div>
<div>
<button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded
font-medium">Post</button>
</div>
</form>
#if ($posts->count())
#foreach ($posts as $post)
<div class="mb-4">
{{ $post->user->username }}
<span class="text-gray-600 text-sm">{{ $post->created_at->diffForHumans() }}</span>
<p class="mb-2">{{ $post->body }}</p>
</div>
#endforeach
{{ $posts->links() }}
#else
There are no posts...
#endif
</div>
</div>
#endsection
UserFactory.php
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'username' => $this->faker->username,
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
}
User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'username',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts(){
return $this->hasMany(Post::class);
}
}
PostFactory.php
<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Post::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'body' => $this->faker->sentence(20),
];
}
}
Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable= [
'body',
'user_id',
];
/**
* Get the user that owns the Post
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
It was because I had an existing user_id in my code so, I deleted it from the database and it worked
Related
This is my model Ticket, when I want to create a ticket, I get error:
Call to undefined method
Illuminate\Database\Eloquent\Relations\BelongsToMany::users()
I don't know how to get rid of it.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tickets extends Model
{
use HasFactory;
public function users()
{
return $this->belongsToMany(User::class, "user_tickets");
}
public function user_ticket()
{
return $this->belongsToMany(user_ticket::class);
}
}
I think the problem comes from the BelongsTo relation but I don't know how to correct it.
This is my pivot Model table that im using
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class user_ticket extends Model
{
use HasFactory;
protected $filable=[
'user_id',
'tickets_id',
];
public function users()
{
return $this->HasMany(User::class, 'id');
}
public function tickets()
{
return $this->HasMany(Tickets::class, 'id');
}
} ```
And this is my User Model
```
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
'role_id',
];
protected $table = 'users';
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
'role_id',
];
public function tickets()
{
return $this->belongsToMany(Tickets::class, 'id');
}
public function roles()
{
return $this->hasOne(Role::class);
}
public function user_ticket()
{
return $this->belongsToMany(user_tickets::class);
}
} ```
And this is where im Using it
```
#extends('dashboard')
#section('contenu')
<div class="creer">
<a href="{{ route('tickets.create') }}"class="btn-creer">
Créer un ticket
</a>
</div>
#csrf
<div class="small-header anim" style="--delay: .3s">Vos Tickets</div>
<table class="table table-striped">
<thead>
<th></th>
<th id="titre"><b>Titre</b></th>
<th id="titre">Description</th>
<th id="titre">Statut</th>
<th id="titre">Date de creation </th>
</thead>
<tbody>
#foreach ($tickets as $ticket)
{{ dd($ticket->user_ticket()->users()) }}
#if (Auth::id() == $ticket->user_id)
#endif
<tr ng-repeat="data in information | filter:search">
<td></td>
<td>{{ $ticket->Titre }}</td>
<td>
#if (strlen($ticket->Description) > 20)
{{ substr($ticket->Description, 0, 20) }}...
#else
{{ $ticket->Description }}
#endif
</td>
<td>{{ $ticket->Statut }}</td>
<td>{{ $ticket->created_at }}</td>
<td>
<a href="{{ route('tickets.edit', $ticket->id) }}">
<span class="fa fa-edit" aria-hidden="true"
ng-click="editInfo(data)"><br><small>Modifier</small></span></a>
</td>
<td>
<a onclick="return confirm('Voulez-vous supprimer votre ticket ?')"
href="{{ route('destroy', $ticket->id) }}">
<span class="fa fa-trash" aria-hidden="true"
ng-click="deleteInfo(data)"><br><small>Supprimer</small></span></a>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
My goal is to show the ticket that an User did create to himself and the Admins. How can i show it using the Gate Method ?
I'm creating a clone for a website where parents can create a list of things they need for their newborn baby so other people can buy it for them as a gift.
At this moment I've managed to insert data into my table and to link that row of data to the user id (so user who is logged in and completed the form).
I've managed to show all the lists from all the user id's but when I go to the dashboard of the authenticated user, I only want to show the lists who is linked to his user_id.
I can't get it working but I'm sure I have to use hasMany() and belongsTo().
This is my code:
My migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique;
$table->binary('password');
$table->enum('role', ['user','admin'])->default('user');
$table->timestamp('created_at');
$table->timestamp('updated_at');
});
Schema::create('lists', function (Blueprint $table)
{
$table->increments('id');
$table->foreignId('user_id')->nullable()->constrained()->onDelete('cascade');
$table->string('baby');
$table->string('vader');
$table->string('moeder');
$table->integer('telefoonnummer');
$table->string('email');
$table->string('adres');
$table->integer('huisnummer');
$table->string('toevoeging')->nullable();
$table->string('stad');
$table->integer('postcode');
$table->string('land');
});
}
My User model:
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function birthLists()
{
return $this->hasMany(Birthlist::class, 'user_id');
}
}
My Birthlist model:
class Birthlist extends Model
{
use HasFactory;
protected $table = 'lists';
protected $primaryKey = 'id';
protected $fillable =
[
'user_id',
'baby',
'vader',
'moeder',
'telefoonnummer',
'email',
'adres',
'huisnummer',
'toevoeging',
'stad',
'postcode',
'land'
];
public $timestamps = false;
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}
My controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Birthlist;
class DashController extends Controller
{
public function dashboard($id)
{
$userId = Auth::id();
$lists = Birthlist::where('user_id')->first();
return view('dashboard', [
'lists' => $lists,
]);
}
}
My view
<body class="bg-red-100 w-screen h-screen pb">
<main class="">
<div class="text-center p-8 bg-green-100">
<p class="">welkom</p>
<h2 class="text-3xl font-bold">{{ Auth::user()->name }}</h2>
</div>
<section class="bg-red-100">
<span class="p-4"><p class="text-center text-xl font-semibold">Mijn lijsten</p></span>
#foreach ($lists->birthLists as $list)
<div class="bg-red-200 p-8 bg-gradient-to-b from-green-300 to-fuchsia-400 drop-shadow-xl text-white md:w-5/12 xl:w-3/12">
<div class="text-3xl font-bold">
{{ $list->baby }}
</div>
<div class="flex flex-row justify-between">
{{ $list->vader }} & {{ $list->moeder }}
</div>
</div>
#endforeach
</section>
</main>
#include('partials.footer')
</body>
In User model :
public function birthLists()
{
return $this->hasMany(Birthlist::class);
}
and in view :
<body class="bg-red-100 w-screen h-screen pb">
<main class="">
<div class="text-center p-8 bg-green-100">
<p class="">welkom</p>
<h2 class="text-3xl font-bold">{{ Auth::user()->name }}</h2>
</div>
<section class="bg-red-100">
<span class="p-4"><p class="text-center text-xl font-semibold">Mijn lijsten</p></span>
#foreach (auth()->user()->birthLists as $list)
<div class="bg-red-200 p-8 bg-gradient-to-b from-green-300 to-fuchsia-400 drop-shadow-xl text-white md:w-5/12 xl:w-3/12">
<div class="text-3xl font-bold">
{{ $list->baby }}
</div>
<div class="flex flex-row justify-between">
{{ $list->vader }} & {{ $list->moeder }}
</div>
</div>
#endforeach
</section>
</main>
#include('partials.footer')
</body>
and don't need to get data from controller because you can get birthLists in blade file.
How can I make that on clicking submit button, match the users to each other, like "Secret Santa" rules? You should not be Santa of yourself, and you should not be Santa of someone who is already your Santa. After that I'm gonna filter with user->groups (Tags shown on photo)
This is my .blade.php:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('List') }}</div>
<div class="card-body">
<form action="">
#foreach($users as $user)
<div class="users-list" style="padding: 5px 0">
<h5>{{ $user->name }}</h5>
<p class="badge badge-primary">{{ $user->group }}</p>
</div>
#endforeach
<input class="btn btn-primary w-100" type="submit" value="Submit">
</form>
</div>
</div>
</div>
</div>
#endsection
And this is my RegisterController.php:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'group' => $data['group'],
'wish' => $data['wish'],
'password' => Hash::make($data['password']),
]);
}
}
I've been trying to get past this error for almost 2 days now. Needless to say, I'm still pretty new to Laravel. I'm using the Laravel's registration form (with some modifications) and I'm storing that User data in a table called "customusers" in my Database. That data includes their name/email/gender/description etc. And I'm trying to use a Resource Controller to basically print and edit that data. The problem I'm facing is, whenever I try to echo the data on my main page, it gives me the error "Property [id] does not exist on this collection instance" or email/name. But when I echo the data with Auth::user()->id, it works. And that's fine, it's do-able if I only wanted to echo data. But I also want to edit that data and I'm gonna have to use my Model for that. So following is my code:
Display.blade.php:
<div id="wrapper">
<div id="content">
<div id="card">
<div id="front">
<div id="top-pic"></div>
<div id="avatar"><span style="position: absolute;padding-top: 17px;margin-left: 34px;color: #fff;font-size: 64px;" class="h5">
{{ Auth::user()->name[0] }}
</span></div>
<div id="info-box">
<div class="info">
<h1>{{ Auth::user()->name }}</h1>
<h2>{{ Auth::user()->message }}</h2>
</div>
</div>
<div id="social-bar">
<a href="{{ Auth::user()->facebook }}" target="_blank">
<i class="fa fa-facebook"></i>
</a>
<a href="{{ Auth::user()->twitter }}" target="_blank">
<i class="fa fa-twitter"></i>
</a>
{{ link_to_route('display.edit','',[$customusers->id],['class'=>'fa fa-edit']) }}
</div>
</div>
Edit.blade.php:
{!! Form::model($customusers,array('route'=>['display.store',$customusers->id],'method'=>'PUT')) !!}
<div class="form-group">
{!! Form::text('name',null,['class'=>'form-control','placeholder'=>'Name']) !!}
</div>
<div class="form-group">
{!! Form::email('email',null,['class'=>'form-control','placeholder'=>'Email']) !!}
</div>
<div class="form-group form-row">
<div class="col-5">
{!! Form::select('gender', ['Male' => 'Male', 'Female' => 'Female'], null, ['class'=>'form-control','placeholder'=>'Choose Gender']); !!}
</div>
<div class="col">
{!! Form::text('facebook',null,['class'=>'form-control','placeholder'=>'Facebook ID']) !!}
</div>
<div class="col">
{!! Form::text('twitter',null,['class'=>'form-control','placeholder'=>'Twitter Handle']) !!}
</div>
</div>
<div class="form-group">
{!! Form::textarea('message',null,['class'=>'form-control','placeholder'=>'Talk about yourself']) !!}
</div>
<div class="form-group">
{!! Form::button('Create',['type'=>'submit','class'=>'btn btn-danger col-lg-12']) !!}
</div>
{!! Form::close() !!}
ProfileController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CustomUser;
use Illuminate\Support\Facades\DB;
class ProfileController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$customusers = CustomUser::all();
return view ('display',compact('customusers'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(CustomUser $customusers)
{
return view ('edit',compact('customusers'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, CustomUser $customusers)
{
$customusers->update($request->all());
return redirect()->route('display.index');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
CustomUser.php (Model):
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class CustomUser extends Authenticatable
{
use Notifiable;
protected $table = 'customusers';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name','username','email','gender','password','message','twitter','facebook',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Web.php (Routes):
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::resource('/display','ProfileController');
So as you can see, I'm using compact in index() function to feed it all the user data in my database, and when I dd($customusers) - it does show me the data in array. But when I use {{ $customusers->name }} - it gives me an error saying "Property [name] does not exist on this collection instance". And thus, the same occurs whenever I try to use link_to_route('display.edit','',[$customusers->id],'') for redirecting the user to the Edit page. Please help me see what I'm doing wrong here. I previously made a CRUD app and I basically did the same things and it all worked perfectly. So I'm not understanding what the problem here is..
You need to loop customers data:
#foreach($customusers as $customer)
{{ link_to_route('display.edit','',[$customer->id],['class'=>'fa fa-edit']) }}
#endforeach
Or you can edit the current logged in data.
{{ link_to_route('display.edit','',[Auth::user()->id],['class'=>'fa fa-edit']) }}
$customusers->all() return a Collection (array of models)
$customers = [ {}, {}, {}, {} ]
So when you try to get the property name or any other it's undefined
You need to loop throw in the view:
#foreach($customusers as $customer)
// Here you have access to all Properties of each $customer
#endforeach
Basically you are passing all users ( collection of data ) to the view by compact.
you've to use foreach loop to access those data.
try loop through in view
#foreach($customusers as $customuser)
{{ link_to_route('display.edit','',[$customuser->id],['class'=>'fa fa-edit']) }}
#endforeach
it will work
As I see your display blade file. You want to edit that user who is Authenticate.Auth
So that point you need to use FindOrFail() method in your controller file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CustomUser;
use Illuminate\Support\Facades\DB;
use Auth;
class ProfileController extends Controller
{
public function index()
{
$id = Auth::user()->id;
$customusers = CustomUser::FindOrFail($id);
return view ('display',compact('customusers'));
}
}
And Use display.blade.php file like:
{{ link_to_route('display.edit','',[$customuser->id],['class'=>'fa fa-edit']) }}
Of if you want to return all the data then use below code:
#foreach($customusers as $customuser)
#if($customuser->id == Auth::user()->id);
{{ link_to_route('display.edit','',[$customuser->id],['class'=>'fa fa-edit']) }}
#endif
#endforeach
The controller as it is:
public function index()
{
$customusers = CustomUser::all();
return view ('display',compact('customusers'));
}
I have a promblem with displaing errors of form that upload file.
Entity:
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
/**
* Class Document
*
* #package Cfw\SiteBundle\Entity
* #ORM\Entity(repositoryClass="Cfw\SiteBundle\Entity\Repository\Document\DocumentRepository")
* #ORM\HasLifecycleCallbacks
* #ORM\Table
*/
class Document
{
use IdentityEntity;
use TimestampableEntity;
CONST UPLOAD_LIMIT = 10;
/**
* Document path
* #var string
*
* #ORM\Column(type="text", length=255, nullable=false)
*/
protected $path;
/**
* #var string
*
* #ORM\Column(type="text", length=50, nullable=false)
*/
protected $type;
/**
* #var string
*
* #ORM\Column(type="text", length=255, nullable=false)
*/
protected $name;
/**
* Image file
*
* #var File
*
*/
protected $file;
....
}
Form Type:
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DocumentType extends AbstractType
{
/**
* #var ContainerInterface $container
*/
protected $container;
/**
* DocumentType constructor.
* #param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'file',
null,
[
'required' => false,
'attr' => [
'label' => false,
'title' => 'form.document.browse',
],
'validation_groups' => ['Default', 'Document'],
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'error_bubbling' => true,
'data_class' => 'Cfw\SiteBundle\Entity\Document\Document',
'translation_domain' => 'messages',
'cascade_validation' => true,
'validation_groups' => ['Default', 'Document'],
]
);
}
public function getName()
{
return 'cfw_document';
}
}
Controller:
public function documentAction(Request $request)
{
/**
* #var $user \Cfw\UserBundle\Entity\User
*/
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
$form = $this->createForm('cfw_document');
$form->handleRequest($request);
if ($form->isValid()) {
$this->get('cfw.document')->uploadDocument($form->getData(), $user);
}
return $this->render(
'CfwUserBundle:Profile:document.html.twig',
[
'form' => $form->createView(),
'documents' => $this->get('cfw.document')->getUserDocuments($user),
'upload_limit' => $this->get('cfw.document')->getUploadLimit(),
]
);
}
View:
{{ form_start(form) }}
<div class="col-lg-8 document-form">
<div class="row form-message">
{{ form_errors(form) }}
</div>
<div class="row">
<h3>{{ 'form.document.title'|trans }}</h3>
</div>
<div class="row">
<div class="col-lg-12 col-md-12">
{{ 'form.document.description'|trans }}
</div>
</div>
<div class="row top10">
<div class="col-lg-6 col-md-6">
{{ form_widget(form.file) }}
</div>
<div class="col-lg-6 col-md-6">
{{ 'form.document.allowed_types'|trans }}<br />
<span class="allowed-size">{{ 'form.document.allowed_size'|trans }}</span>
</div>
</div>
<div class="row">
<div class="col-md-4 col-lg-4 submit-block">
<button type="submit" class="btn btn-warning btn-block">{{ 'form.document.submit'|trans }}</button>
</div>
</div>
</div>
{{ form_end(form) }}
Validation config is:
Cfw\SiteBundle\Entity\Document\Document:
properties:
file:
- File:
maxSize: "10M"
mimeTypes: ["image/jpeg", "image/gif", "image/png", "image/tiff", "application/pdf"]
maxSizeMessage: document.file.wrong_size
mimeTypesMessage: document.file.wrong_format
groups: [Default, Document]
Trouble is if I upload zip file need to display error of wrong type. But, nothing is displaying, also file is not uploaded (when is pdf or image is ok).
if change in view to {{ form_errors(form.file) }} errors are displayed, but I think is not correct. In profiler error shown on field file, but $form->getErrors() is empty.
Can somebody say what is wrong?
I get error in DocumentType. Need to add
'error_bubbling' => true
to the field "file", not to setDefaults()