getErros stays empty even when there are errors - symfony

My action:
public function profile(Request $request): Response
{
$form = $this->createForm(UserUpdateType::class, options: [
'action' => $this->generateUrl('app_profile'),
'method' => 'POST'
]);
if ($request->getMethod() === 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
} else {
dd($form->getErrors());
}
}
return
$this->renderForm('login/profile.html.twig', [
'form' => $form
])
;
}
Giving example with this field:
->add('_password', PasswordType::class, [
'label' => 'New Password',
'attr' => [
'class' => 'form-control'
],
'constraints' => [
new Length([
'min' => 6
])
]
])
Even when I set a password like 123, which is clearly shorter than what is expected (6), getErrors() returns empty array.

Related

How to add text that there are no search results for such entered word to a custom block?

I have a view that searches for indexed entity fields using context filters. I added a custom block to the view like this:
{{ drupal_block('result_entity_product_categories', {arguments}) }}
This block displays categories that match the entered word in the search. If you enter something for which there are no search results, for example, bbbbb, I need to display something like this:
Sorry
No results for: "bbbbb"
But here are some of our most popular products
P.S. The option to add text to the No Results Behavior view setting is not suitable. It is necessary to add text in the custom block.
The build() method code of my custom block:
public function build() {
$configuration = $this->getConfiguration();
$term = $configuration['arguments']['0'] ?: '';
if (empty($term)) {
return '';
}
$index = $this->entityTypeManager->getStorage('search_api_index')->load('entity_product_index');
$parse_mode = $this->parseModeManager->createInstance('terms');
$parse_mode->setConjunction('AND');
$search_query = $index->query();
$search_query->setParseMode($parse_mode)
->keys($term);
$search_result = $search_query->execute();
$rows = [];
foreach ($search_result->getResultItems() as $item) {
if (($node = $item->getOriginalObject()->getEntity()) && ($node instanceof NodeInterface)) {
$categoryKey = $node->get('field_entity_product_category')->getString();
if ($categoryKey) {
++$rows[$categoryKey];
}
}
}
$build['container'] = [
'#type' => 'container',
'#attributes' => [
'class' => ['category-counter-wrapper'],
],
];
foreach ($rows as $key => $count) {
if ($node = $this->entityTypeManager->getStorage('node')->load($key)) {
$build['container'][$key] = [
'#type' => 'container',
'#attributes' => [
'class' => ['item'],
],
'label' => [
'#type' => 'container',
'#markup' => $node->getTitle(),
'#attributes' => [
'class' => ['label'],
],
],
'count' => [
'#type' => 'container',
'#markup' => $count,
'#attributes' => [
'class' => ['count'],
],
],
'link' => [
'#type' => 'link',
'#url' => Url::fromUserInput($node->get('field_custom_url')->getString(), ['query' => ['text' => $term]]),
'#attributes' => [
'class' => ['link'],
],
],
];
}
}
return $build;
}

Symfony Dynamic Form - Get file from embedded form gives NULL

I have a dynamic form which display/hide a FileType field depending on another field value (link).
When i'm trying to get the file in my controller, it always gives me NULL
My UserType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('familyStatus', ChoiceType::class, [
'label' => 'Statut de famille',
'label_attr' => [
'class' => 'fg-label'
],
'attr' => [
'class' => 'sc-gqjmRU fQXahQ'
],
'required' => true,
'choices' => [
'Married' => 'M',
'Single' => 'S'
]
]);
$formModifier = function (FormInterface $form, $status = null) {
if ($status === 'M') {
$form->add('familyInfo', FamilyInfoType::class);
}
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$user = $event->getData();
$formModifier($event->getForm(), $user->getFamilyStatus());
}
);
$builder->get('familyStatus')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$status = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $status);
}
);
}
My FamilyInfoType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('partnerName', TextType::class, [
'label' => 'Nom du partenaire',
'label_attr' => [
'class' => 'fg-label'
],
'attr' => [
'class' => 'sc-gqjmRU fQXahQ'
],
'required' => true
])
->add('weddingProof', FileType::class, [
'label' => 'Acte de mariage',
'label_attr' => [
'class' => 'Upload-label'
],
'attr' => [
'class' => 'Upload-input',
'maxsize' =>'4M',
'accept' =>'image/*'
],
'required' => false,
'mapped' => false
]);
}
My UserController:
/**
* #Route("/user", name="add_user", methods={"GET", "POST"})
* #param Request $request
*/
public function addUser(Request $request) {
$response = [];
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($user->getFamilyStatus() === 'M') {
var_dump("ok");
$document = $form->get('familyInfo')->get('weddingProof')->getData();
$partnerName = $form->get('familyInfo')->get('partnerName')->getData();
var_dump($document); // NULL
var_dump($partnerName); // OK the value is displayed
die;
}
}
return $this->render("user/registration.html.twig", ['form' => $form->createView()]);
}
It's working with TextType field but not with FileType. What's wrong with my form.
The issue is with the mapped => false option to the file type. The form is not setting the uploaded file object in the property of your entity because it’s not mapped.

I'm trying to create multi login in laravel 5.7 and this error appeared, can anyone help me?

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given, called in C:\laragon\www\hotel\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php on line 123
<?php
namespace App\Http\Controllers\Auth;
use App\User;use App\Admin;use App\GestionnaireReceptionniste;use App\GestionnaireResto;use App\Http\Controllers\Controller;use Illuminate\Support\Facades\Hash;use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
$this->middleware('guest:admin');
$this->middleware('guest:gestionnairereceptionniste');
$this->middleware('guest:gestionnaireresto');
}
public function showAdminRegisterForm()
{
return view('auth.register', ['url' => 'admin']);
}
public function showGestionnaireReceptionnisteRegisterForm()
{
return view('auth.register', ['url' => 'gestionnairereceptionniste']);
}
public function showGestionnaireRestoRegisterForm()
{
return view('auth.register', ['url' => 'gestionnairesto']);
}
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:6', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
protected function createAdmin(Request $request)
{
$this->validator($request->all())->validate();
$admin = Admin::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/admin');
}
protected function createGestionnaireReceptionniste(Request $request)
{
$this->validator($request->all())->validate();
$gestionnairereceptionniste = GestionnaireReceptionniste::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/gestionnairereceptionniste');
}
protected function createGestionnaireResto(Request $request)
{
$this->validator($request->all())->validate();
$gestionnaireresto =CreateGestionnaireResto::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/admin');
}
}
models:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admin';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class GestionnaireReceptionniste extends Authenticatable
{
use Notifiable;
protected $guard = 'gestionnairereceptionniste';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class GestionnaireResto extends Authenticatable
{
use Notifiable;
protected $guard = 'gestionnaireresto';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
guard:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'gestionnairereceptionniste' => [
'driver' => 'session',
'provider' => 'gestionnaireceptionnistes',
],
'gestionnaireresto' => [
'driver' => 'session',
'provider' => 'gestionnairerestos',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'gestionnairereceptionnistes' => [
'driver' => 'eloquent',
'model' => App\GestionnaireReceptionniste::class,
],
'gestionnairerestos' => [
'driver' => 'eloquent',
'model' => App\GestionnaireResto::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
ReditectIfAuthenticated:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "admin" && Auth::guard($guard)->check()) {
return redirect('/admin');
}
if ($guard == "gestionnairereceptionniste" && Auth::guard($guard)->check()) {
return redirect('/gestionnairereceptionnister');
}
if ($guard == "gestionnairesto" && Auth::guard($guard)->check()) {
return redirect('/gestionnairesto');
}
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
There is a typo in your config/auth.php file.
This:
'gestionnairereceptionniste' => [
'driver' => 'session',
'provider' => 'gestionnaireceptionnistes', // <-- typo
],
should be:
'gestionnairereceptionniste' => [
'driver' => 'session',
'provider' => 'gestionnairereceptionnistes',
],

Use Expression constrainst on non object

I have a form like it:
class FeatureDynamicSequenceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('upstream', IntegerType::class, [
'data' => 0,
'constraints' => [
new LessThan([
'value' => 1000,
]),
],
])
->add('downstream', IntegerType::class, [
'data' => 0,
'constraints' => [
new LessThan([
'value' => 1000,
]),
],
])
->add('showUtr', CheckboxType::class,[
'data' => true,
'label' => 'Show UTR',
'required' => false,
])
->add('showIntron', CheckboxType::class,[
'data' => true,
'required' => false,
])
;
}
}
In this form, I would like add a Constrainst that check:
If showUtr or ShowIntron are not checked, then upstream and downstreal can't be > to 0.
Then I want something like it:
->add('upstream', IntegerType::class, [
'data' => 0,
'constraints' => [
new LessThan([
'value' => 1000,
]),
new Expression([
'expression' => 'value > 0 && (this.showUtr || this.showIntron)',
'message' => 'You cannot set upstream if you do not display UTRs and introns.',
]),
],
])
But I can't use it, because it's not an object, value give me the value of the upstream field (it's ok), but I can't access to the showUtr or showIntron value...
EDIT: try with Callback closure
->add('upstream', IntegerType::class, [
'data' => 0,
'constraints' => [
new LessThan([
'value' => 1000,
]),
new Callback([
'callback' => function($data, ExecutionContextInterface $executionContectInterface) {
dump($data);
$executionContectInterface->addViolation('You cannot set upstream if you do not display UTRs and introns.');
},
])
],
])
I have the same problem, $data just contain the field value.
I don't really want to create an Entity, because I don't persist it... And I can't believe there is not a solution to check it whithout creating an Entity.
I answered in a previous question here
I solved it by using:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'constraints' => [
new Callback([
'callback' => function($data, ExecutionContextInterface $executionContectInterface) {
if ($data['upstream'] > 0 && (!$data['showUtr'] || !$data['showIntron'])) {
$executionContectInterface->buildViolation('You cannot set upstream if you do not display UTRs and introns.')
->atPath('[upstream]')
->addViolation()
;
}
},
]),
],
]);
}
The full code is:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('upstream', IntegerType::class, [
'data' => 0,
'constraints' => [
new LessThan([
'value' => 1000,
]),
],
])
->add('downstream', IntegerType::class, [
'data' => 0,
'constraints' => [
new LessThan([
'value' => 1000,
]),
],
])
->add('showUtr', CheckboxType::class, [
'data' => true,
'label' => 'Show UTR',
'required' => false,
])
->add('showIntron', CheckboxType::class, [
'data' => true,
'required' => false,
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'constraints' => [
new Callback([
'callback' => function($data, ExecutionContextInterface $executionContectInterface) {
if ($data['upstream'] > 0 && (!$data['showUtr'] || !$data['showIntron'])) {
$executionContectInterface->buildViolation('You cannot set upstream if you do not display UTRs and introns.')
->atPath('[upstream]')
->addViolation()
;
}
},
]),
],
]);
}

Send choice Value instead choice key from Symfony form

I need to send from Symfony form ChoiceType::class
But I don't need choices keys, I need to send choices values.
Is that is possible?
$form->add('section', ChoiceType::class, array(
'mapped' => false,
'choices' => array(
1 => 'value1',
2 => 'value2'
),
));
I just want to send value1 if I chose value1,
not key 1 as default.
You can use
array_flip ($array)
refer to php docs
[Since Symfony 2.7] In any case you can play with choice value through choice_value option and a Closure function (Reference):
$form->add('section', ChoiceType::class, array(
'choice_value' => function ($value, $key, $index) {
return $value;
}
));
Useful for dynamic choices.
You just need to reverse it. Also, I don't think you need 'mapped'.
Try this:
$form->add(
'section',
ChoiceType::class,
[
'choices' => [
'value1' => 1,
'value2' => 2,
],
]
);
It should work.
Mayby a bit late but i've made this and it works perfect. Without array_flip. Mayby for someone it 'll be usefull.
$dataUsers = [];
$users = [
['id' => 1, 'firstname' => 'joe', 'lastname' => 'doe'],
['id' => 2, 'firstname' => 'will', 'lastname' => 'fog'],
];
foreach ($users as $u) {
$dataUsers[] = (object)['id' => $u['id'], 'label' => $u['firstname']];
}
$builder
->add('users', ChoiceType::class, [
'choices' => $dataUsers,
'choice_label' => function ($value) {
if (is_object($value)) {
return $value->label;
} else {
return 0;
}
},
'choice_value' => function ($value) {
if (is_object($value)) {
return $value->id;
} else {
return 0;
}
},
'data' => (object)[ 'id' => 2]
]);

Resources