Symfony Check if user exist in database - php

I am looking for a solution in my controller to check before sending a form if the user already exists in the database. Here is my action on which I would like to implement this.
/**
* Creates a new invite entity.
*
* #Route("/inscription", name="invite_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$invite = new Invite();
$form = $this->createForm(InviteType::class, $invite);
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($invite);
$em->flush();
$this->get('app_mailer')->sendMailInscriptionMjml($invite, $this->getParameter('client_mail_to'));
$this->get('session')->getFlashBag()->add('success', 'Votre inscription à été pris en compte.');
} else {
$this->get('session')->getFlashBag()->add('error', 'Une erreur est survenue.');
}
return $this->redirect($this->generateUrl('invite_show', array('id' => $invite->getId())));
}
return $this->render('#App/invite/new.html.twig', array(
'invite' => $invite,
'form' => $form->createView(),
));
}
Thank you for your help

You shouldn't need to do this in the controller. This is basic entity validation and Symfony comes with built in constraints to handle this sort of thing.
Assuming you are using a User Entity similar to below in your Symfony application you need only apply a unique validation constraint to the user class and specify which properties you want to test against for uniqueness. This example will validate that the user is unique by email, and throw an exception if not.
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/** #UniqueEntity(
* fields={"email"},
* errorPath="email",
* message="It appears you have already registered with this email."
*)
*/
class User
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string $email
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
* #Assert\Email()
*/
protected $email;
// ...
}
Pay notice to the #UniqueEntity("email") annotation on the class and the use statements. Of course you'll need to adopt this logic to your user class.
// controller action
public function newAction(Request $request)
{
$invite = new Invite();
$form = $this->createForm(InviteType::class, $invite);
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($invite);
$em->flush();
$this->get('app_mailer')->sendMailInscriptionMjml(
$invite, $this->getParameter('client_mail_to')
);
$this->get('session')->getFlashBag()
->add('success', 'Votre inscription à été pris en compte.');
return $this->redirect(
$this->generateUrl(
'invite_show', array(
'id' => $invite->getId()
)
)
);
}
}
return $this->render('#App/invite/new.html.twig', array(
'invite' => $invite,
'form' => $form->createView(),
));
}
For more on this:
https://symfony.com/doc/current/reference/constraints/UniqueEntity.html

// Pass in the entity manager to your form via options
// Do this before you call $this->createForm:
// $options['entityManager'] = $this->getDoctrine()->getManager();
// then call $form = $this->createForm(InviteType::class, $invite, $options);
// Inside your form type i.e. InviteType
$em = $options['entityManager'];
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$user = $data['user']; // this needs to be whatever you called user in your form
$userRepo = $em->getRepository('User'); // this needs to be the location of your user repository
if ($userRepo->findOneBy(['user' => $user])) { // you need to pick a field that determines how you will search for the user via the repository
$form->addError(new FormError('User already exists'));
}
}
);

<div class="container accroche">
<h5>{{ 'Inscription aux évenements'|trans }}</h5>
<p>Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500,
quand un peintre anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique,
sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles Letraset contenant des passages du Lorem Ipsum, et, plus récemment,
par son inclusion dans des applications de mise en page de texte, comme Aldus PageMaker.
</p>
</div>
{{ form_start(form, {attr: {novalidate: 'novalidate','id':'formValidate'}}) }}
<div class="middle">
<div class="middle_form">
<div class="container">
<div class="stepwizard">
<div class="stepwizard-row setup-panel col-md-12 text-center">
<div class="stepwizard-step col-md-3">
1
</div>
<div class="stepwizard-step col-md-3">
2
</div>
<div class="stepwizard-step col-md-3">
3
</div>
<div class="stepwizard-step col-md-3">
4
</div>
</div>
</div>
<div class="row setup-content" id="step-1">
<div class="col-md-12">
<h3>{{ 'Informations invités'|trans }}</h3>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.name, {'attr': {'class': 'validate', 'id': 'last_name'}}) }}
{{ form_errors(form.name) }}
<label for="last_name">{{ 'Nom'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.surname, {'attr': {'class': 'validate', 'id': 'surname'}}) }}
{{ form_errors(form.surname) }}
<label for="surname">{{ 'Prénom'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.email, {'attr': {'class': 'validate', 'id': 'email'}}) }}
{{ form_errors(form.email) }}
<label for="email">{{ 'E-mail'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="row">
<div class="col-12">
<label>{{ 'Présence'|trans }} <sup>*</sup></label>
{{ form_widget(form.dispo, {'attr': {'class': 'validate', 'id': 'dispo'}}) }}
{{ form_errors(form.dispo) }}
</div>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-md-12">
<h3>{{ 'Informations participants'|trans }}</h3>
<div class="row">
<ul class="customers"
data-prototype="{{ form_widget(form.customers.vars.prototype)|e('html_attr') }}">
{% for customers in form.customers %}
<div class="row">
<div class="input-field col-12">
{{ form_row(customers.name, {'attr': {'class': 'validate', 'id': 'name'}}) }}
{{ form_errors(customers.name) }}
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_row(customers.surname, {'attr': {'class': 'validate', 'id': 'surname'}}) }}
{{ form_errors(customers.surname) }}
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_row(customers.old) }}
{{ form_errors(customers.old) }}
</div>
</div>
{% endfor %}
</ul>
</div>
<button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-md-12">
<h3>Logements</h3>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.housing, {'attr': {'class':'validate'}}) }}
{{ form_errors(form.housing) }}
<label>{{ 'Comment allez vous vous logez ?'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.hotel, {'attr': {'class':'validate'}}) }}
{{ form_errors(form.hotel) }}
<label>{{ 'Hôtel'|trans }} <sup>*</sup></label>
</div>
</div>
<button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
</div>
</div>
<div class="row setup-content" id="step-4">
<div class="col-md-12">
<h3>{{ 'Arrivée/Départ'|trans }}</h3>
<div class="row">
<div class="col-12">
<label>{{ 'Date d\'arrivée'|trans }} <sup>*</sup></label>
{#<input class="datepicker" type="text" id="dateArrival" name="form[dateArrival]"/>#}
{{ form_widget(form.dateArrival, {'attr': {'class': 'datepicker validate'}}) }}
{{ form_errors(form.dateArrival) }}
</div>
</div>
<div class="row">
<div class="col-12">
<label>{{ 'Date de départ'|trans }} <sup>*</sup></label>
{#<input class="datepicker" type="text" id="dateDeparture" name="form[dateDeparture]"/>#}
{{ form_widget(form.dateDeparture, {'attr': {'class': 'datepicker validate'}}) }}
{{ form_errors(form.dateDeparture) }}
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.transport, {'attr': {'class':'validate'}}) }}
{{ form_errors(form.transport) }}
<label>{{ 'Transport utilisé'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="btn-center">
<button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
{{ form_widget(form.save, {'attr': {'class':'btn btn-success', 'id':'SaveAccount'}}) }}
</div>
</div>
</div>
</div>
</div>
</div>
{{ form_widget(form.dateArrival, {'attr': {'class': 'hidden'}}) }}
{{ form_widget(form.dateDeparture, {'attr': {'class': 'hidden'}}) }}
{{ form_end(form) }}

First, get the id $id = #YourId;. You can then select the user using SQL. SELECT * FROM [user_table] WHERE id = $id; If the result holds a user, then the user exists.

Related

Symfony 5 form fields appear when they should not

I display with twig a form for adding an event, with the possibility at the same time to create a new account if no user is connected. So I have one form integrated with another, my UserType form is integrated with my EventType form.
I made a condition that if the user is logged in, we will not display the registration form. Only that of event creation.
Here is my code :
{{ form_start(form) }}
{% if form.vars.valid == false %}
<div class="alert alert-danger">
Des erreurs ont été relevées. Merci de vérifier le formulaire.
</div>
{% endif %}
{% if app.user == false %}
<div id="general_info">
<h4> <i class="ion-ios-information"></i> À propos de vous</h4>
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.user.lastName, {'label': 'Votre nom *', 'attr': {'class': 'filter-input'}}) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.user.firstName, {'label': 'Votre prénom *', 'attr': {'class': 'filter-input'}}) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.user.password.first, {'label': 'Votre mot de passe *', 'attr': {'class': 'filter-input'}}) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.user.email, {'label': 'Votre adresse email *', 'attr': {'class': 'filter-input'}}) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.user.password.second, {'label': 'Confirmez votre mot de passe *', 'attr': {'class': 'filter-input'}}) }}
</div>
</div>
</div>
</div>
{% endif %}
<div id="event_and_category">
<h4><i class="ion-ios-list-outline"></i> Nom & Catégorie</h4>
<div class="row">
<div class="col-md-6">
{{ form_row(form.title) }}
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.category) }}
</div>
</div>
</div>
</div>
<div id="date_and_location">
<h4><i class="ion-ios-location"></i> Date & Localisation</h4>
<h5>Où se déroule votre événement ?</h5>
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.location) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.address) }}
{{ form_row(form.latitude) }}
{{ form_row(form.longitude) }}
</div>
</div>
<div class="col-md-6"></div>
<div class="col-md-6 no-padding mar-bot-20">
<div id="map"></div>
</div>
</div>
<h5>Quand se déroule votre événement ?</h5>
<div class="row">
<div class="col-md-6">
<div id="datepicker-from" class="input-group date" data-date-format="dd/mm/yyyy">
{{ form_row(form.startDate) }}
<span class="input-group-addon"><i class="icofont-ui-calendar"></i></span>
</div>
</div>
<div class="col-md-6">
<div id="datepicker-to" class="input-group date" data-date-format="dd/mm/yyyy">
{{ form_row(form.endDate) }}
<span class="input-group-addon"><i class="icofont-ui-calendar"></i></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.startAt) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.endAt) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.dateDescription) }}
</div>
</div>
</div>
</div>
<div id="event_info">
<h4><i class="ion-ios-calendar-outline"></i> Votre événement</h4>
<h5>Informations de contact</h5>
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.contactName) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.contactEmail) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.contactPhone) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.organisatorEmail) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.organisatorPhone) }}
</div>
</div>
</div>
<h5>Décrivez votre événement</h5>
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.description) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.tags) }}
</div>
</div>
</div>
<h5>Choisissez une image pour votre événement</h5>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="add-listing__input-file-box">
{{ form_row(form.coverFile) }}
<div class="add-listing__input-file-wrap">
<i class="ion-ios-cloud-upload"></i>
<p>Ajoutez une photo ou une image</p>
</div>
</div>
</div>
</div>
</div>
<h5>Bulletin d'inscription</h5>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<form class="photo-upload">
<div class="form-group">
<div class="add-listing__input-file-box">
{{ form_row(form.registrationForm) }}
<div class="add-listing__input-file-wrap">
<i class="ion-ios-cloud-upload"></i>
<p>Ajoutez un fichier</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<h5>Réseaux sociaux</h5>
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.website) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_row(form.facebookPage) }}
</div>
</div>
</div>
<h5>Annonce PREMIUM</h5>
<div class="row">
<div class="col-md-12 annonce-premium">
{{ form_row(form.featured) }}
</div>
</div>
{{ form_row(form._token) }}
{{ form_row(form.save) }}
</div>
{{ form_end(form) }}
So far everything is fine, if I logged in the "about you" part does not appear. My problem is that it appears lower !!
So after my submit button. How to solve this problem ?
In your form_end(form) line, add a flag to tell twig to not render unused forms:
{{ form_end(form, { 'render_rest': false }) }}

How to update only few columns of an Entity by a form

I have a User Entity and I collect all the data in a form called Register. But once after registering, I want to edit some of the fields of a user by a form. But some fields are avoided being updated (email) and Password field is optional. I tried rendering the same register form but $form->handleRequest($request) throws an error saying:
Expected argument of type "string", "NULL" given at property path
"password".
I want to know if there is a way to do this?
I tried $form->submit($request->request->get($form->getName()),false);
instead of $form->handleRequest($request); but it didn't work.
// This is my controller.
/**
* #Route("/update/{id}", name="update")
* #param $id
* #param Request $request
* #param UserPasswordEncoderInterface $passwordEncoder
* #param UserRepository $userRepository
* #return \Symfony\Component\HttpFoundation\RedirectResponse|Response
*/
public function updateUser($id,Request $request, UserPasswordEncoderInterface $passwordEncoder, UserRepository $userRepository){
$user = $userRepository->find($id);
$form = $this->createFormBuilder($user)
->add('email',EmailType::class,[
'label'=>'Email',
'required' => false,
'attr'=>['placeholder'=>"Email"]
])
->add('password',RepeatedType::class,[
'type' => PasswordType::class,
'invalid_message' => 'The password fields must match.',
'required' => false,
'options' => ['attr' => ['class' => 'password-field']],
'first_options' => ['label' => 'Password','attr'=>['placeholder'=>"Password"]],
'second_options' => ['label' => 'Confirm Password','attr'=>['placeholder'=>"Confirm Password"]],
])
->add('firstName',TextType::class,['label'=>'First Name', 'attr'=>['placeholder'=>"First Name"]])
->add('lastName',TextType::class,['label'=>'Last Name','attr'=>['placeholder'=>"Last Name"]])
->add('address',TextareaType::class,['required' => false,'label'=>'Address','attr'=>['placeholder'=>"Address"]])
->add('idNumber',TextType::class,['label'=>'NIC Number','attr'=>['placeholder'=>"NIC Number"]])
->add('phoneNumber',TelType::class,['label'=>'Phone Number','attr'=>['placeholder'=>"Phone Number"]])
->add('image',FileType::class,['label'=>'Photo','required'=>false,'attr'=>['hidden'=>"hidden", 'accept'=>"image/jpeg, image/png"]])
->add('save',SubmitType::class,[
'label'=>'Register',
'attr' => [
'class'=>"btn btn-outline-success float-right"
]
])
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
if($user->getPassword() !=""){
$user->setPassword($passwordEncoder->encodePassword($user,$user->getPassword()));
}
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirectToRoute('home');
}
return $this->render('register/update.html.twig', [
'form'=>$form->createView(),
]);
}
// And this is my TWIG file.
{% extends 'base.html.twig' %}
{% block title %}Edit Info{% endblock %}
{% block refHome %}{{ path('main') }}{% endblock %}
{% block body %}
<div class="container" style=" margin-left: auto;margin-right: auto;margin-top: 1cm;" >
<div class="row">
{# <div class="col-lg-2"></div>#}
<div class="col-lg-10">
<div class="card" style="width: 50rem;text-align: center;">
<div class="card-body">
<h3 class="card-title float-left">Edit Info</h3>
<div style="margin-top: 2cm;">
<p class="card-text">
<form name="register" id="register_form" method="post" enctype="multipart/form-data">
<div id="register">
<div class="container">
<div class="row">
<div class="col-sm-5">
{{ form_errors(form.firstName) }}
{{ form_widget(form.firstName) }}
</div>
<div class="col-sm-2"></div>
<div class="col-sm-5">
{{ form_errors(form.lastName) }}
{{ form_widget(form.lastName) }}
</div>
</div>
<div style="margin-top: 0.5cm;"></div>
<div class="row">
<div class="col-sm-6">
{{ form_errors(form.email) }}
{{ form_widget(form.email) }}
</div>
<div class="col-sm-1"></div>
<div class="col-sm-5">
{{ form_errors(form.idNumber) }}
<input type="text" id="register_idNumber" placeholder="NIC Number" onkeypress="isInputNumber(event)" pattern="^[0-9]{9}[a-zA-Z]$" value="{{ form.idNumber.vars.value }}" name="register[idNumber]" required="required" class="form-control" " /> <div class="input-group-append">
</div>
</div>
</div>
<div style="margin-top: 0.5cm;"></div>
<div class="row">
<div class="col-sm-5">
<div style="margin-top: 0.5cm;"></div>
{{ form_errors(form.phoneNumber) }}
<input type="tel" id="register_phoneNumber" value="{{ form.phoneNumber.vars.value }}" name="register[phoneNumber]" onkeypress="isPhone(event)" required="required" placeholder="Phone Number" class="form-control" pattern="^[0-9]{10}$" />
</div>
<div class="col-sm-2"></div>
</div>
<div style="margin-top: 0.5cm;"></div>
<div class="row" >
<div class="col-sm-7">
{{ form_errors(form.address) }}
{{ form_widget(form.address) }}
</div>
<div class="col-sm-1" hidden="hidden">
{{ form_widget(form.image) }}
</div>
</div>
<div style="margin-top: 0.5cm;"></div>
<div class="form-group row">
<div class="col-sm-7">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="defaultUnchecked" style="float: left">
<label class="custom-control-label" for="defaultUnchecked">Change Password</label>
</div>
</div>
</div>
<div style="margin-top: 0.5cm;"></div>
<div id="register_password" >
<div class="form-group row">
{% for passwordField in form.password %}
<div class="col-sm-5">
{{ form_errors(passwordField) }}
{{ form_widget(passwordField) }}
</div>
<div class="col-sm-2"></div>
{% endfor %}
</div>
<div style="margin-top: 0.5cm;"></div>
</div>
</div>
{{ form_widget(form.save,{'label':"Update"}) }}
{{ form_widget(form._token) }}
{{ form_errors(form) }}
</form>
</p>
</div>
</div>
</div>
</div>
<div class="col-lg-1"></div>
</div>
</div>
{% endblock %}
{% block javascripts %}
<script>
const checkBoxPwd = document.getElementById('defaultUnchecked');
const pwdDiv = document.getElementById('register_password');
pwdDiv.style.visibility = "hidden";
checkBoxPwd.addEventListener("change",function () {
if (checkBoxPwd.checked == true){
pwdDiv.style.visibility = "visible";
}else{
pwdDiv.style.visibility = "hidden";
}
});
</script>
<script>
function isInputNumber(eve) {
var ch = String.fromCharCode(eve.which);
if (document.getElementById('register_idNumber').value.length < 9){
if (!(/[0-9]/.test(ch))){
eve.preventDefault();
}
}else {
if (!(/[a-zA-Z]/.test(ch))){
eve.preventDefault();
}
}
if (document.getElementById('register_idNumber').value.length > 9){
eve.preventDefault();
}
}
function isPhone(eve) {
var ch = String.fromCharCode(eve.which);
if (!(/[0-9]/.test(ch))){
eve.preventDefault();
}
if (document.getElementById('register_phoneNumber').value.length > 9){
eve.preventDefault();
}
}
</script>
{% endblock %}

symfony- update entity and changed fields

I try editAction in symfony but I have error when if not change input file it update field file in database to null ... how to not update field file if not changed value in update action
code action:
/**
* #Route("/babysitter/update/{id}", name="update_babysitter_by_admin")
*
* #param Request $request
* #param BabySitter $babySitter
* #ParamConverter("id", options={"id": "id"})
*
* #return mixed
*/
public function updateBabySitterAction(BabySitter $babySitter, Request $request){
$em= $this->getDoctrine()->getManager();
$form= $this->createForm(BabySitterType::class, $babySitter,['requiredFile'=> false]);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
if($babySitter->getPicture()->getDocument()){
$this->uploadDocument->upload($babySitter->getPicture(), $this->getParameter('pictures_directory'));
}
if($babySitter->getCriminalRecord()->getDocument()){
$this->uploadDocument->upload($babySitter->getCriminalRecord(), $this->getParameter('criminalRecord_director_babySitter'));
}
if($babySitter->getIdCards()){
$this->uploadDocument->uploadIdCard($babySitter->getIdCards(), $babySitter,$this->getParameter('idCard_directory'));
}
$em->persist($babySitter);
$em->flush();
$url = $this->generateUrl('info_babySitter',['id'=> $babySitter->getId()]);
$response = new RedirectResponse($url);
return $response;
}
return $this->render('admin/registerBabySitter.html.twig',[
'form'=> $form->createView()
]);
}
code twig:
{% trans_default_domain 'FOSUserBundle' %}
<div class="register-box" style="width:460px">
<div class="register-box-body">
<p class="login-box-msg">Register a new BabySitter</p>
{{ form_start(form, {'method':'post', 'attr': {'class': 'fos_user_registration_register', 'novalidate': 'novalidate'}}) }}
<div class="form-group has-feedback">
{{ form_widget(form.email,{'attr': {'class': 'form-control', 'placeholder': 'Email'}}) }}
{{ form_errors(form.email) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.firstName,{'attr': {'class': 'form-control', 'placeholder': 'FirstName'}}) }}
{{ form_errors(form.firstName) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.lastName,{'attr': {'class': 'form-control', 'placeholder': 'LastName'}}) }}
{{ form_errors(form.lastName) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.plainPassword.first,{'attr': {'class': 'form-control', 'placeholder': 'Password'}}) }}
{{ form_errors(form.plainPassword.first) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.plainPassword.second,{'attr': {'class': 'form-control', 'placeholder': 'Repeat Password'}}) }}
{{ form_errors(form.plainPassword.second) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.genre,{'attr': {'class': 'form-control', 'placeholder': 'Genre'}}) }}
{{ form_errors(form.genre) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.dateBirth,{'attr': {'class': 'form-control', 'placeholder': 'date Birthday'}}) }}
{{ form_errors(form.dateBirth) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.linkVideo,{'attr': {'class': 'form-control', 'placeholder': 'link Video'}}) }}
{{ form_errors(form.linkVideo) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.criminalRecord) }}
{{ form_errors(form.criminalRecord) }}
</div>
<div class="form-group has-feedback">
<ul id="idCard-fields-list"
data-prototype="{{ form_widget(form.idCards.vars.prototype)|e }}"
data-widget-tags="{{ '<li></li>'|e }}">
{{ form_row(form.idCards) }}
{% for idCardField in form.idCards %}
<li>
{{ form_errors(idCardField) }}
{{ form_widget(idCardField) }}
</li>
{% endfor %}
</ul>
<div class="row">
<button type="button"
class="add-another-collection-widget-idCard btn btn-primary btn-flat"
data-list="#idCard-fields-list">Add another idCard</button>
</div>
</div>
<div class="form-group has-feedback">
{{ form_widget(form.nbrYears,{'attr': {'class': 'form-control', 'placeholder': 'Number Years'}}) }}
{{ form_errors(form.nbrYears) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.rib,{'attr': {'class': 'form-control', 'placeholder': ' rib'}}) }}
{{ form_errors(form.rib) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.presentation,{'attr': {'class': 'form-control', 'placeholder': 'presentation'}}) }}
{{ form_errors(form.presentation) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.adress) }}
{{ form_errors(form.adress) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.availability) }}
{{ form_errors(form.availability) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.assignement) }}
{{ form_errors(form.assignement) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.qualification) }}
{{ form_errors(form.qualification) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.picture) }}
{{ form_errors(form.picture) }}
</div>
<div class="form-group has-feedback">
<ul id="language-fields-list"
data-prototype="{{ form_widget(form.languages.vars.prototype)|e }}"
data-widget-tags="{{ '<li></li>'|e }}">
{{ form_widget(form.languages) }}
{% for languageField in form.languages %}
<li>
{{ form_errors(languageField) }}
{{ form_widget(languageField) }}
</li>
{% endfor %}
</ul>
<div class="row">
<button type="button"
class="add-another-collection-widget btn btn-primary btn-flat"
data-list="#language-fields-list">Add another language</button>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="{{ 'registration.submit'|trans }}">
</div>
<!-- /.col -->
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
<!-- /.form-box -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('.add-another-collection-widget').click(function (e) {
var list = jQuery(jQuery(this).attr('data-list'));
// Try to find the counter of the list or use the length of the list
var counter = list.data('widget-counter') | list.children().length;
// grab the prototype template
var newWidget = list.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/__name__/g, counter);
// Increase the counter
counter++;
// And store it, the length cannot be used if deleting widgets is allowed
list.data('widget-counter', counter);
// create a new list element and add it to the list
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
newElem.appendTo(list);
addTagFormDeleteLink(newElem);
});
function addTagFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<button class="btn btn-danger btn-flat" style="margin-top:2%;margin-left:50%" type="button">Delete this Language</button>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
jQuery('.add-another-collection-widget-idCard').click(function (e) {
var list = jQuery(jQuery(this).attr('data-list'));
// Try to find the counter of the list or use the length of the list
var counter = list.data('widget-counter') | list.children().length;
// grab the prototype template
var newWidget = list.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/__name__/g, counter);
// Increase the counter
counter++;
// And store it, the length cannot be used if deleting widgets is allowed
list.data('widget-counter', counter);
// create a new list element and add it to the list
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
if(counter <= 3){ newElem.appendTo(list); }
});
function addIdCardFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<button class="btn btn-danger btn-flat" style="margin-top:2%;margin-left:50%" type="button">Delete this idCard</button>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
});
</script>
when i update entity and i not update field file i have field file in database null ... how to update entity without changed in input file

Laravel Typer error: Argument 1 passed to must be an instance of . string given

I'm trying to update the values of a customer phone number, a customer has many phones, but when I try to update the phone number I get this error:
Type error: Argument 1 passed to
App\Repositories\Backend\Cliente\ClienteRepository::updateTelefono()
must be an instance of App\Models\Cliente\Cliente, string given,
called in
/Applications/MAMP/htdocs/sgc18/app/Http/Controllers/Backend/Cliente/ClienteController.php
on line 159
On my ClienteRepository I have this code:
public function updateTelefono(Cliente $cliente, Telefono $telefono, array $data) : Telefono
{
return DB::transaction(function () use ($cliente, $telefono, $data) {
if ($telefono->update([
'telefono' => $data['telefono'],
'tipo_telefono_id' => $data['tipo_telefono_id'],
'comentario' => $data['comentario']
])) {
event(new ClienteTelefonoUpdated($telefono));
return $telefono;
}
throw new GeneralException(__('Hubo un problema al actualizar el teléfono. Intentelo de nuevo.'));
});
}
in my ClienteController I have this code:
public function updateTelefono(ClienteRequest $request, $cliente_id, $telefono_id)
{
$cliente = Cliente::findOrfail($cliente_id);
$telefono = Telefono::findOrFail($telefono_id);
$this->clienteRepository->updateTelefono($cliente, $telefono, $request->only(
'telefono',
'tipo_telefono_id',
'comentario'
));
return redirect()->to(route('admin.clientes.show', $cliente_id) . '#telefonos')->withFlashSuccess(__('Teléfono actualizado correctamente.'));
}
This is the route for update:
Route::patch('{id}/telefono/{tid}/update', 'ClienteController#updateTelefono')->name('telefono.update');
admin/clientes/{id}/telefono/{tid}/update | admin.clientes.telefono.update | App\Http\Controllers\Backend\Cliente\ClienteController#updateTelefono
And this is my edit view:
#extends('backend.layouts.app')
#section('title', __('Administración de Clientes') . ' | ' . __('Editando Teléfono de Cliente') . ' ' . $cliente->nombre_completo . ' | ' . app_name())
#section('breadcrumb-links')
#include('backend.clientes.includes.breadcrumb-links')
#endsection
#section('content')
<div class="card">
<div class="card-body">
<div class="row">
<div class="col">
<h4 class="card-title mb-0">
{{ __('Administración de Clientes') }}
<small class="text-muted">({{ __('Editando Teléfono de Cliente') }} <b>{{ $cliente->nombre_completo }}</b>)</small>
</h4>
</div>
</div>
<hr />
{{ html()->modelForm($tel, 'PATCH', route('admin.clientes.telefono.update', [$cliente->id, $tel->id]))->open() }}
<div class="row mt-4 mb-4">
<div class="col">
{{ html()->label(__('Número de Teléfono'))->for('telefono') }}
{{ html()->text('telefono')
->class('form-control')
->attribute('maxlength', 191) }}
</div>
</div>
<div class="row mt-4 mb-4">
<div class="col">
{{ html()->label(__('Tipo Teléfono'))->for('tipo_telefono_id') }}
{{ html()->hidden('cliente_id')->value($cliente->id) }}
<select class="form-control tipoTelefono" name="tipo_telefono_id">
#if(isset($tipo_telefonos) && $tipo_telefonos->count() > 0)
#foreach($tipo_telefonos as $i)
<option value="{{ $i->id }}" #if($i->id == old('tipo_telefono_id', $tel->tipo_telefono_id)) selected #endif>{{ $i->descripcion }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="row mt-4 mb-4">
<div class="col">
{{ html()->label(__('Comentario'))->for('comentario') }}
{{ html()->textarea('comentario')->class('form-control')->attribute('rows', 4)->attribute('noresize') }}
</div>
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col">
{{ form_cancel(route('admin.clientes.show', $cliente->id) . '#telefonos', __('Cancelar')) }}
</div><!--col-->
<div class="col text-right">
{{ form_submit(__('Actualizar')) }}
</div><!--row-->
</div><!--row-->
</div><!--card-footer-->
</div>
{{ html()->closeModelForm() }}
#endsection
#push('after-scripts')
<script type="text/javascript">
$(document).ready(function(){
$('.tipoTelefono').select2();
});
</script>
#endpush
It seems that you are passing $cliente_id as the id of the client not as instance of a Client.
Try to find the Client first:
public function updateTelefono(ClienteRequest $request, $cliente_id, $telefono_id)
{
$cliente = \App\Models\Cliente\Cliente::find($cliente_id);
$telefono = \App\Models\Cliente\Telefono::find($telefono_id);
$this->clienteRepository->updateTelefono($cliente, $telefono, $request->only(
'telefono',
'tipo_telefono_id',
'comentario'
));
return redirect()->to(route('admin.clientes.show', $cliente_id) . '#telefonos')->withFlashSuccess(__('Teléfono actualizado correctamente.'));
}

ErrorException, array_merge(): Argument #2 is not an array when i work a call Ajax

In my users page, I use a div with two tabs "Products" and "Followers", in the second tab, I've a pagination for the list of followers.
Not return to the tab "Products" when I try the pagination, I user a call Ajax.
But when I try to run it, I have a error 500, and the response of the get is :
{"error":{"type":"ErrorException","message":"array_merge(): Argument #2 is not an
array","file":"\/Users\/utilisateur\/Desktop\/mamp\/ptf-l4\/vendor\/laravel\/framework\
/src\/Illuminate\/View\/Environment.php","line":117}}
I don't know why and I don't know how to find a solution.
This is my controller :
public function show($id){
// récupère les données de l'user et les produis qu'il partage
$show = $this->api->show($id);
// décode le json pour qu'il se réaffiche en array pour pouvoir l'exploiter
$json = json_decode($show->getContent());
$json->followed = User::userFollowedPaginate($id);
LaravelMixpanel::identify(Auth::user()->mixpanel_id);
LaravelMixpanel::track('User show view');
if(Request::ajax())
{
$html = View::make('users.show', $json)->render();
return Response::json(['html' => $html]);
}
return View::make('users.show')
->with('user', $json);
}
My API/Controller :
public function show($id){
// récupère donnée de l'user et les produits qu'il échange
$data = User::with(array('products' => function($query){
$query->whereNull('shared_at');
$query->whereNull('deleted_at');
}))->findOrFail($id)->toArray();
// récupère le nb de produits qu'il échange en ce moment
$data['nbShareCurrently'] = Product::where('user_id', $id)->whereNull('shared_at')->whereNull('deleted_at')->count();
// récupère le nb de produits qu'il a échangé depuis le début
$data['nbShared'] = Product::where('user_id', $id)->whereNotNull('shared_at')->count();
return Response::json($data, 200);
}
My JS :
function callAjaxUser(url) {
$.ajax ({
type: "GET",
url: url ,
success: function() {
console.log('Success ');
},
error: function() {
console.log('Error ');
}
});
}
$(document).ready(function(){
$('body').on('click', ' .pagination a ', function(event){
event.preventDefault();
var url=$(this).attr('href');
callAjaxUser(url);
});
});
And my view :
#extends('default')
#section('title')
Fiche de {{ $user->name }}
#stop
#section('contenu')
<section class="panel col-lg-8 col-sm-8 m-t-large">
<header class="panel-heading m-l-n m-r-n">
<ul class="nav nav-tabs pull-right">
<li class="active"><i class="icon-list icon-large text-default"></i>Mes produits en cours de partage</li>
<li><i class="icon-group icon-large text-default"></i>Mes abonnés</li>
</ul>
<span class="hidden-sm">Fiche technique du frigo</span>
</header>
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane active" id="product">
<div class="col-lg-3">
{{-- dd($user) --}}
<h4>{{{ $user->name }}}</h4>
#if($user->photo && File::exists(public_path().'/uploads/photos/users/'.e($user->photo)))
{{ HTML::image('uploads/photos/users/'.e($user->photo), e($user->name)) }}
#else
{{ HTML::image('template/images/avatar.jpg', e($user->name)) }}
#endif
#if($user->id!=Auth::user()->id)
#if(DB::table('user_followers')->where('user_followed', $user->id)->where('user_following', Auth::user()->id)->count()==0)
{{ HTML::decode(HTML::linkAction('UserFollowersController#follow', '<i class="icon-heart">S\'abonner</i>', array('id' => $user->id), array('class' => 'btn btn-info m-t-large m-b-small'))) }}
#else
{{ HTML::decode(HTML::linkAction('UserFollowersController#unfollow', '<i class="icon-heart">Se désabonner</i>', array('id' => $user->id), array('class' => 'btn btn-danger m-t-large m-b-small '))) }}
#endif
#endif
</div>
<div class="col-lg-9">
<h4>Le frigo contient en ce moment :</h4>
<ul class="list-unstyled">
#foreach($user->products as $product)
<li class="list-group-item bg m-b-small">
<div class="media">
#if(e($product->photo) && File::exists(public_path().'/uploads/photos/products/'.e($product->photo)))
<span class="pull-left img-product">
<a href="{{ URL::action('ProductsController#show', $product->id) }}">
{{ HTML::image('uploads/photos/products/'.e($product->photo), e($product->title), array('class' => 'img-rounded')) }}
</a>
</span>
#endif
<div class="media-body">
<div>{{{ $product->title }}}</div>
<p>{{{ $product->description }}}</p>
<p class="pull-left">Quantité : <span class="label label-info">{{{ $product->quantity }}}</span></p>
<p class="pull-right">Prix : <span class="badge bg-danger">{{{ $product->price }}} €</span></p>
</div>
</div>
</li>
#endforeach
</ul>
<div class="pagination">
{{-- $users->products->links() --}}
</div>
</div>
</div>
<div class="tab-pane" id="follow">
<div class="row m-b-large">
#if($user->followed!=NULL)
#foreach($user->followed as $user_followed)
<div class="panel col-lg-2 m-l-large m-t-large ">
<div class="col-lg-8 m-b-n-small col-md-offset-2 m-t-large text-center">
#if($user_followed->photo && File::exists(public_path().'/uploads/photos/users/'.e($user_followed->photo)))
{{ HTML::image('uploads/photos/users/'.e($user_followed->photo), e($user_followed->name), array ( 'class' => 'img-circle')) }}
#else
{{ HTML::image('template/images/avatar.jpg', e($user_followed->name), array ( 'class' => 'img-circle')) }}
#endif
<h3>{{{ $user_followed->name }}}</h3>
</div>
<div class="col-lg-10 m-b-small center ">
#if(DB::table('user_followers')->where('user_followed', $user_followed->id)->where('user_following', Auth::user()->id)->count()==0)
{{ HTML::decode(HTML::linkAction('UserFollowersController#follow', '<i class="icon-heart">S\'abonner</i>', array('id' => $user_followed->id), array('class' => 'btn btn-info btn-group-justified m-t-large m-b-small'))) }}
#else
{{ HTML::decode(HTML::linkAction('UserFollowersController#unfollow', '<i class="icon-heart">Se désabonner</i>', array('id' => $user_followed->id), array('class' => 'btn btn-danger btn-group-justified m-t-large m-b-small '))) }}
#endif
</div>
</div>
#endforeach
#else
<div class="panel col-lg-8 col-lg-offset-2 m-t-large">
<h4> Tu ne suis actuellement personne </h4>
</div>
#endif
</div>
<div class="col-lg-12">
{{ $user->followed->links() }}
</div>
</div>
</div>
</div>
</section>
#stop
#section('js')
{{ Basset::show('usersPaginate.js') }}
#endsection
I stumbled upon this question because it is the first Google search result for laravel ErrorException, array_merge(): Argument #2 is not an array.
Even though the question is a year old, it is still relevant, because this happened to me in Laravel 5.0 today.
Without taking the time to digest all of your code, the problem is likely the same in your case as it was in mine: you are passing a non-array as the second argument to view::make() (whether intentionally or not) when you must pass an array.
The problem line is this one, in your controller:
$html = View::make('users.show', $json)->render();
Given that $json appears to be an object, the fix is simple:
$html = View::make('users.show', compact('json'))->render();
Hopefully, this answer will help somebody else in the future.

Categories