Matching users to each other - php

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']),
]);
}
}

Related

Attempt to read property "username" on null

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

How to solve logout issue in Laravel 7?

I have been looking for answer and tried many answer from the community here, but none of them seems to work in my case.
All was working before migration from Bootstrap to TailwindCss, now when i click logout, nothing happens.
I'm not sure if it's a javascript related issue, i hope you guys can help me with this.
auth.blade.php
<div class="hidden md:flex items-center justify-end space-x-8 md:flex-1 lg:w-0">
<span class="inline-flex rounded-md shadow-sm">
<a href="{{ route('logout') }}"
onclick="event.preventDefault(); document.getElementById('logout-form').submit();"
class="whitespace-no-wrap inline-flex items-center justify-center px-4 py-2 border border-transparent text-base leading-6 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition ease-in-out duration-150">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</span>
</div>
Auth::routes();
Route::get('/login/applicant', 'Auth\LoginController#showApplicantLoginForm')->name('login');
Route::get('/login/employer', 'Auth\LoginController#showEmployerLoginForm');
Route::get('/register/applicant', 'Auth\RegisterController#showApplicantRegisterForm')->name('register');
Route::get('/register/employer', 'Auth\RegisterController#showEmployerRegisterForm');
// route::post('/logout', 'Auth\LoginController#logout')->name('logout');
Route::post('/login/applicant', 'Auth\LoginController#applicantLogin');
Route::post('/login/employer', 'Auth\LoginController#employerLogin');
Route::post('/register/applicant', 'Auth\RegisterController#createApplicant');
Route::post('/register/employer', 'Auth\RegisterController#createEmployer');
Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:applicant')->except('logout');
$this->middleware('guest:employer')->except('logout');
}
public function showApplicantLoginForm()
{
return view('auth.login', ['url' => 'applicant']);
}
public function applicantLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('applicant')->attempt([
'email' => $request->email,
'password' => $request->password
], $request->get('remember'))) {
return redirect()->intended('/applicant');
}
return back()->withInput($request->only('email', 'remember'));
}
public function showEmployerLoginForm()
{
return view('auth.login', ['url' => 'employer']);
}
public function employerLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('employer')->attempt([
'email' => $request->email,
'password' => $request->password
], $request->get('remember'))) {
return redirect()->intended('/employer');
}
return back()->withInput($request->only('email', 'remember'));
}
}

SQLSTATE [23000]: Integrity limitation violation: 1062 'mail#mail.com' duplicate entry for 'users_email_unique' key

I have a registration form. When the email is registered in the database it gets an error message
SQLSTATE [23000]: Violation of integrity restrictions: 1062 Duplicate entry 'mail#mail.com' for 'users_email_unique' key
I want to avoid that mistake and instead get a warning like "registered email" or something similar. Any help is appreciated. This is my code.
controller/auth/registercontroller.php
<?php
namespace VMS\Http\Controllers\Auth;
use VMS\User;
use VMS\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
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|min:4',
'id_level' => 'required',
'email' => 'required|min:4|email|unique:users',
'password' => 'required',
'confirm' => 'required|same:password',
'g-recaptcha-response' => 'required|captcha',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \VMS\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'id_level' => $data['id_level'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
public function store(Request $request)
{
$name = $request->input('name');
$id_level = $request->input('id_level');
$email = $request->input('email');
$password = $request->input('password');
$user = User::create([
'name' => $name,
'id_level' => $id_level,
'email' => $email,
'password' => Hash::make($password)
]);
if($user) {
return response()->json([
'success' => true,
'message' => 'Register Berhasil!'
], 201);
} else {
return response()->json([
'success' => false,
'message' => 'Register Gagal!'
], 400);
}
}
}
User.php (Model)
<?php
namespace VMS;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'id_level', 'email', 'password',
];
/**
* 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',
];
protected $connection = 'vms_db';
}
register.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>SI-BeLa</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<main class="py-4">
<div class="container" style="margin: 0; min-width: 100%">
<div class="row">
<div class="col-sm-6" style="text-align: ; padding-right: 20px;">
#guest
<a class="logo" href="{{ url('/') }}">{{ __('SI-BeLa') }}</a>
#endguest
</div>
<div class="col-sm-6" style="text-align: center;">
<h2 class="title">
<br><br>
<div style="text-align: center;">REGISTER
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('register') }}" method="post">
{{ csrf_field() }}
<div class="cont_form_sign_up text-center">
<br>
<input type="text" class="form-control2" placeholder="Nama" id="name" name="name" pattern=".{4,}" required="required" title="Paling sedikit 4 karakter">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Nama paling sedikit 4 Karakter</p>
<input type="hidden" class="form-control2" value="9" id="id_level" name="id_level">
<input type="email" class="form-control2" placeholder="E-mail" id="email" name="email" required="required" pattern="[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Email harus aktif & Pastikan email belum terdaftar di SIBeLa</p>
<input type="password" id="pw1" name="password" class="form-control2" placeholder="Password"
required="required" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Password paling sedikit 8 karakter serta mengandung angka, huruf kecil dan besar</p>
<input type="password" id="pw2" name="confirm" class="form-control2" placeholder="Confirm Password" required="required">
<div class="form-group">
<center>
{!! NoCaptcha::renderJs() !!}
{!! NoCaptcha::display() !!}
<span class="text-danger">{{ $errors->first('g-recaptcha-response') }}</span>
</center>
</div>
<a class="btn btn-linkk" href="/loginpl">
{{ __('Kembali ke login') }}
</a>
<br>
<button class="button gd-btn btn-2 btn-primaryy" onclick="cambiar_sign_up()"><strong>REGISTER</strong> </button>
</div>
</form>
</div>
</h2>
</div>
</div>
</div>
</main>
How do I make a notification alert if the email is registered?
You have to use like this. Remove unique:users from validation
return Validator::make($data, [
'name' => 'required|min:4',
'id_level' => 'required',
'email' => 'required|min:4|email',
'password' => 'required',
'confirm' => 'required|same:password',
'g-recaptcha-response' => 'required|captcha',
]);
you must use laravel validation in your controller for validate request parameters.
first add this use top of your controller
use Illuminate\Support\Facades\Validator;
then in your registercontroller define this method
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'password' => 'required|max:10',
'name' => 'nullable|string|max:50',
]);
if ($validator->fails()) {
$response = $validator->errors();
session()->flash('flash_error', $response);
return redirect()->back();
}
/**
* create new user
*/
try {
/**
* new user
*/
User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
} catch (Exception $e) {
throw new HttpException(500, $e->getMessage());
}
session()->flash('flash_success', 'you are registered.');
return redirect()->back();
}
by default email field in laravel is unique and for validate it we use this exception :
unique:users
users is table name.
to learn more about laravel validation
see this link
https://laravel.com/docs/7.x/validation
to access validation errors in view file
we pass errors flash session with name flash_error
you can show it for example like this:
#if(session()->has('flash_error'))
<ul>
#foreach(session()->get('flash_error') as $error)
<li>{{ session()->get('flash_error') }}</li>
#endforeach
</ul>
#endif
and show success message with bootstrap like this:
#if(session()->has('flash_success'))
<div class="alert alert-success" role="alert">
{{ session()->get('flash_success') }}
</div>
#endif

Unable to fetch and update DB columns in Laravel (using Resource Controller & Collective Forms)

Here's a little context to what I'm trying to do: I'm trying to make a Profile System where the user registers and is redirected to a Display Page, where all the User info like his name, email etc. are meant to be displayed. Since the registration form only has 2 fields (name / email) - the user has to update his other info like his gender/facebook ID/twitter ID etc etc. So I've an Edit button which takes the user to a form. Now on that form, I want his already-existing Name/Email to show up, while the other fields like Gender/FB/Twitter/Description are empty - once he fills those fields and presses Update, I want him to go back to Display Page and then be shown all this updated/new information i.e Gender/Name/Email/Twitter/Description. Following is my code so far:
ProfileController.php (Resource Controller):
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CustomUser;
class ProfileController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$customusers = CustomUser::get()->first();
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 $customuser)
{
return view ('edit',compact('customuser'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, CustomUser $customuser)
{
$customuser->update($request->all());
return redirect()->route('display.index')->with('creation','Profile has been updated successfully!');
}
/**
* 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',
];
}
Display.blade.php (Main Page):
#extends('layouts.app')
#section('content')
<div style="margin-top: 5.2%;" class="container">
<div class="row">
<div class="col-lg-12">
#if (Session::has('creation'))
<div class="alert alert-info">
{{ Session::get('creation') }}
</div>
#endif
{{ link_to_route('display.edit','Edit',[$customusers->id],['class'=>'btn btn-success']) }}
{{$customusers->name}}
{{$customusers->email}}
{{$customusers->message}}
{{$customusers->facebook}}
{{$customusers->twitter}}
</div>
</div>
</div>
#endsection
And finally, this is my Edit.blade.php:
#extends('layouts.app')
#section('content')
<body style="height: 105.6vh;">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header" style="color: #fff; background-color: #113;font-family: 'Nunito',sans-serif; text-transform: uppercase;letter-spacing: 2px;
font-weight: bold;">
Edit Profile
</div>
<div class="card-body">
{!! Form::model($customuser,array('route'=>['display.update',$customuser->id],'method'=>'PUT')) !!}
<div class="form-group">
{!! Form::text('name',null,['class'=>'form-control','placeholder'=>'Username']) !!}
</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('Edit',['type'=>'submit','class'=>'btn btn-danger col-lg-12']) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
</body>
#endsection
Now, when I click Edit and go to Edit.blade.php - all the fields are blank, when two of them (Name / Email) should have pre-filled blanks of what the user's credentials are, but that isn't the case - they are blank. And when I fill all the fields and press Update, it gives me "The PUT method is not supported for this route. What am I doing wrong here? I've been squabbling through the Internet for over 2 hours and I'm unable to find what I'm doing wrong here. Let me know there are any further info required for you to crack this problem of mine..

Symfony2 File upload form don't display errors

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()

Categories