0

I try to insert an 'activity' in the database. The 'Activite' entity has a relation oneToMany with the 'Deplacement' entity and the 'Deplacement' a ManyToOne with 'Activite'.

In the controller, I first persist and flush the activity entered by the user, then I set the deplacement field 'activite' to the activite id and then persist and flush the deplacement linked to that activity.

The problem comes from the activite id when I assign it to the Deplacement object, as it is considered null. The IdActivite field from activite entity is a SERIAL int.

I've tried to set manually the activity ID to '1' but the system still considered it as null. Then I've tried fetching the activite object in the database through it's ID and then pass it to the $dep->setActivite($activiteObject); but the error message stays the same.

Entity activite.php

<?php
/**
* Activite
*
* @ORM\Table(name="schemaName.activite", indexes=  {@ORM\Index(name="IDX_FC4F2FE89859C8", columns={"categorie_idcategorie"}),  @ORM\Index(name="IDX_FC4F2F13285AF2", columns={"projet_idprojet"}),  @ORM\Index(name="IDX_FC4F2F8FD472D9", columns={"tache_idtache"})})
* @ORM\Entity(repositoryClass="BundleName\Entity\ActiviteRepository")
*/
class Activite
{
 /**
 * @var integer
 *
 * @ORM\Column(name="id_activite", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="SEQUENCE")
 *        @ORM\SequenceGenerator(sequenceName="fiche_activite_sic.activite_id_activite_seq", allocationSize=1, initialValue=1)
 */
 private $idActivite;
 public function getIdActivite(){return $this->idActivite;}
 public function setIdActivite($value){$this->idActivite;return $this;}

/**
 * @var string
 *
 * @ORM\Column(name="nom_activite", type="string", nullable=false)
 */
private $nomActivite;
public function getNomActivite(){return $this->nomActivite;}
public function setNomActivite($value){$this->nomActivite=$value;return $this;}

/**
 * @var string
 *
 * @ORM\Column(name="description_activite", type="text", nullable=false)
 */
private $descriptionActivite;
public function getDescriptionActivite(){return $this->descriptionActivite;}
public function setDescriptionActivite($value){$this->descriptionActivite=$value;return $this;}

/**
 * @var \DateTime
 *
 * @ORM\Column(name="date_debut", type="datetime", nullable=true)
 */
private $dateDebut = 'now()';
public function getDateDebut(){return $this->dateDebut;}
public function setDateDebut($value){$this->dateDebut=$value;return $this;}
public function getDateDebutFormat(){return $this->getDateDebut()->format('Y-m-d');}

/**
 * @var \DateTime
 *
 * @ORM\Column(name="date_fin", type="datetime", nullable=true)
 */
private $dateFin;
public function getDateFin(){return $this->dateFin;}
public function setDateFin($value){$this->dateFin=$value;return $this;}
public function getDateFinFormat(){return $this->getDateFin()->format('Y-m-d');}

/**
 * @var \categorie
 *
 * @ORM\ManyToOne(targetEntity="Categorie")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="categorie_idcategorie", referencedColumnName="id_categorie")
 * })
 */
private $categorie;
public function getCategorie(){ return $this->categorie;}
public function setCategorie($Categorie){$this->categorie = $Categorie; return $this;}

/**
 * @var \projet
 *
 * @ORM\ManyToOne(targetEntity="Projet")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="projet_idprojet", referencedColumnName="id_projet")
 * })
 */
private $projet;
public function getProjet(){return $this->projet;}
public function setProjet($Projet){$this->projet = $Projet; return $this;}

/**
 * @var \tache
 *
 * @ORM\ManyToOne(targetEntity="Tache")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="tache_idtache", referencedColumnName="id_tache")
 * })
 */
private $tache;
public function getTache(){return $this->tache;}
public function setTache($Tache){$this->tache = $Tache; return $this;}


/**
 * @var \FosUser
 *
 * @ORM\ManyToOne(targetEntity="BundleName\Entity\FosUser", inversedBy="activite")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="user_iduser", referencedColumnName="id")
 * })
 */
private $FosUser;
public function getFosUser(){return $this->FosUser;}
public function setFosUser($FosUser){$this->FosUser=$FosUser; return $this;}




/**
 * @ORM\OneToMany(targetEntity="BundleName\Entity\Deplacement", mappedBy="activite", cascade={"persist"})
 */
private $deplacement;
public function getDeplacement(){return $this->deplacement;}
public function setDeplacement($value){$this->deplacement=$value; return $this;}



/**
 * Constructor
 */
public function __construct()
{
    $this->deplacement = new \Doctrine\Common\Collections\ArrayCollection();
}
}

ActiviteType.php

<?php

class activiteType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('nomActivite', 'text', array(
            'label' => 'Activité',
            'attr' => array(
                'class' => 'form-control'
            )

        ))
        ->add('descriptionActivite', 'textarea', array(
            'label' => 'Description',
            'attr' => array(
                'class' => 'form-control'
            )
        ))
        ->add('dateDebut', 'datetime', array(
            'label' => 'Debut',
            'widget' => 'single_text',
            'data' => new \DateTime(),
            'format' => 'dd/MM/yyyy HH:mm',
            'attr' => array(
                'class' => 'form-control',
                'readonly' => 'readonly',
                'style' => 'font-size: 18px',
                'class' => 'BundleName:activite'
            )
        ))
        ->add('dateFin', 'datetime', array(
            'label' => 'Fin',
            'widget' => 'single_text',
            'data' => new \DateTime(),
            'format' => 'dd/MM/yyyy HH:mm',
            'attr' => array(
                'class' => 'form-control',
                //'readonly' => 'readonly',
                'style' => 'font-size: 18px',
                'class' => 'BundleName:activite'
            )
        ))
        ->add('categorie', 'entity', array(
            'label' => 'Catégorie',
            'class' => 'BundleName:Categorie',
            'choice_label' => 'nomCategorie',
            'required' => true,
            'placeholder' => '-- Catégorie... --',
            'attr' => array(
                'class' => 'form-control'
            )
        ))
        ->add('projet', 'entity', array(
            'label' => 'Projet',
            'class' => 'BundleName:Projet',
            'choice_label' => 'nomProjet',
            'empty_value' => '-- Projet ... -- ',
            'attr' => array(
                'class' => 'form-control'
            )
        ))
        ->add('tache', 'entity', array(
            'label' => 'Tâche',
            'class' => 'BundleName:Tache',
            'choice_label' => 'nomTache',
            'empty_value' => '-- choisir --',
            'required' => true,
            'attr' => array(
                'class' => 'form-control'
            ), 
        ))
        /*->add('Site', 'entity', array(
            'label' => 'Site',
            'class' => 'BundleName:Site',
            'choice_label' => 'nomSite',
            'empty_value' => '-- choisir --',
            'attr' => array(
                'class' => 'form-control'
            )
        ))
        ->add('Transport', 'entity', array(
            'label' => 'Véhicule',
            'class' => 'BundleName:Transport',
            'choice_label' => 'nomTransport',
            'empty_value' => '-- choisir --',
            'attr' => array(
                'class' => 'form-control'
            )
        ))*/
        ->add('deplacement', 'collection', array(
            'type' => new DeplacementType(), 
            'options' => array('label' => false),
            'allow_add' => true, 
            'allow_delete' => true,
            'by_reference' => true
        ))
        ->add('reset', 'reset', array(
            'label' => 'Réinitialiser',
            'attr' => array(
                'class' => 'btn btn-warning btn-block'
            )
        ))
        ->add('valider', 'submit', array(
            'label' => 'Valider',
            'attr' => array(
                'class' => 'btn btn-primary btn-block'
            )
        ));
}

/**
 * @param OptionsResolverInterface $resolver
 */
// public function setDefaultOptions(OptionsResolverInterface $resolver)
// {
//     $resolver->setDefaults(array(
//         'data_class' => 'BundleName\Entity\activite'
//     ));
// }

/**
 * @param OptionsResolverInterface $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'BundleName\Entity\activite'
    ));
}

/**
 * @return string
 */
public function getName()
{
    return 'activite';
}
}

FicheController.php

public function declarationActiviteAction(Request $req)
{
    $em = $this->getDoctrine()->getManager();
    $query = $em->getRepository('BundleName:Activite')->findAll();
    $user = $em->getRepository('BundleName:FosUser')->find(1);

    $act = new Activite();
    $form = $this->createForm(new activiteType, $act);
    $form->handleRequest($req);
    $dep = new Deplacement();

    if ($form->isSubmitted() && $form->isValid()) {
        // We set the activity user, persist the activity and flush it to the databse 
        $act->setFosUser($user);
        $em->persist($act);
        $em->flush();

        // Then, we're gonna set the deplacement activity (maybe trouble if we don't set the other fields)
        // Then persist the $dep object and flush it to the database
        $activiteObject = $em->getRepository('BundleName:Activite')->find($act->getIdActivite());
        $dep->setActivite($activiteObject);
        $em->persist($dep);
        $em->flush();
        $msg = "OKAY";
        // $this->addFlash('addActivitySuccess', 'Activité ' . "'" . $act->getNomActivite() . "'" . ' enregistrée !');
        $req->getSession()->getFlashBag()->add('addActivitySuccess', 'Activité ' . "'" . $act->getIdActivite() . "'" . ' enregistrée !');
        return $this->redirectToRoute('declaration_activite', array(
            'msg' => $msg
        ));
    }
    return $this->render('BundleName:Vues:declaration.html.twig', [
        'table' => $query,
        'form' => $form->createView(),
        'title' => $titre
    ]);
}

Deplacement.php

<?php

use Doctrine\ORM\Mapping as ORM;

/**
* Deplacement
*
* @ORM\Table(name="schemaName.deplacement", indexes={@ORM\Index(name="IDX_AA135CF06B901557", columns={"site_depart"}), @ORM\Index(name="IDX_AA135CF0D5E8011A", columns={"site_destination"}), @ORM\Index(name="IDX_AA135CF04E50836D", columns={"activite_idactivite"})})
 * @ORM\Entity(repositoryClass="BundleName\Entity\DeplacementRepository")
 */
class Deplacement
{
/**
 * @var integer
 *
 * @ORM\Column(name="id_deplacement", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="SEQUENCE")
 * @ORM\SequenceGenerator(sequenceName="fiche_activite_sic.deplacement_id_deplacement_seq", allocationSize=1, initialValue=1)
 */
private $idDeplacement;
public function getIdDeplacement(){return $this->idDeplacement;}
public function setIdDeplacement($value){$this->idDeplacement=$value; return $this;}

/**
 * @var \DateTime
 *
 * @ORM\Column(name="date_debut_dep", type="datetime", nullable=true)
 */
private $dateDebutDep = 'now()';
public function getDateDebutDep(){return $this->dateDebutDep;}
public function setDateDebutDep($value){$this->dateDebutDep=$value;return $this;}

/**
 * @var \DateTime
 *
 * @ORM\Column(name="date_fin_dep", type="datetime", nullable=true)
 */
private $dateFinDep;
public function getDateFinDep(){return $this->dateFinDep;}
public function setDateFinDep($value){$this->dateFinDep=$value;return $this;}


/**
 * @var string
 *
 * @ORM\Column(name="km", type="decimal", precision=10, scale=0, nullable=true)
 */
private $km;
public function getKm(){return $this->km;}
public function setKm($value){$this->km=$value;return $this;}

/**
 * @var \Transport
 *
 * @ORM\ManyToOne(targetEntity="BundleName\Entity\Transport", cascade={"persist"})
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="transport_idtransport", referencedColumnName="id_transport")
 * })
 */
private $transport;
public function getTransport(){return $this->transport;}
public function setTransport($value){$this->transport=$value; return $this;}    


/**
 * @var string
 *
 * @ORM\Column(name="temps_sur_site", type="decimal", precision=10, scale=0, nullable=true)
 */
private $tempsSurSite;
public function getTempsSurSite(){return $this->tempsSurSite;}
public function setTempsSurSite($value){$this->tempsSurSite=$value;return $this;}

/**
 * @var \Site
 *
 * @ORM\ManyToOne(targetEntity="BundleName\Entity\Site",  cascade={"persist"})
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="site_depart", referencedColumnName="id_site")
 * })
 */
private $siteDepart;
public function getSiteDepart(){return $this->siteDepart;}
public function setSiteDepart($value){$this->siteDepart=$value; return $this;}

/**
 * @var \Site
 *
 * @ORM\ManyToOne(targetEntity="BundleName\Entity\Site", cascade={"persist"})
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="site_destination", referencedColumnName="id_site")
 * })
 */
private $siteDestination;
public function getSiteDestination(){return $this->siteDestination;}
public function setSiteDestination($value){$this->siteDestination=$value; return $this;}

/**
 * @var \Activite
 *
 * @ORM\ManyToOne(targetEntity="BundleName\Entity\Activite", inversedBy="deplacement", cascade={"persist"})
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="activite_idactivite", referencedColumnName="id_activite")
 * })
 */
private $activite;
public function getActivite(){return $this->activite;}
public function setActivite($value){$this->activite=$value;return $this;}

public function __toString()
{
    $val = strval($this->getIdDeplacement());
    return $val;
}

} 

Error message :

An exception occurred while executing 'INSERT INTO schemaName.deplacement (id_deplacement, date_debut_dep, date_fin_dep, km, temps_sur_site, transport_idtransport, site_depart, site_destination, activite_idactivite) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [55, "2019-07-14 00:00:00", "2019-07-14 00:00:00", 1, -1, 1, 1, 1, null]:

SQLSTATE[23502]: Not null violation: 7 ERREUR: une valeur NULL viole la contrainte NOT NULL de la colonne « activite_idactivite » DETAIL: La ligne en échec contient (55, 00:00:00, 00:00:00, 1, -1, 1, 1, 1, null)

2
  • Can you post the Deplacement entity? Looks like the problem might be in setActivite(). BTW, you don't need to reload $activiteObject, it should be the same as $act.
    – msg
    Jul 14, 2019 at 12:32
  • I updated the post. Yes I had a doubt about that thank you !
    – brn
    Jul 14, 2019 at 12:38

1 Answer 1

0

Why did you find $activiteObject it's the same object as $act. Try to do this:

$act->setFosUser($user);

$em->persist($act);

$em->flush();

Departments are adding to Activity by your form.

And don't omit the bi-directionnal relation in your Entity. See Doctrine documentation for that.

3
  • You were right, I only need to persist the $act object. Though I still get the same issue saying activite_idactivite is null. Yet in the flashbag just after I can get the activite ID
    – brn
    Jul 14, 2019 at 13:42
  • Did you add the bi-directionnal relation? If you don't want bi-directionnal relation you may do like this:
    – Stoads
    Jul 14, 2019 at 13:56
  • If you don't want bi-directionnal relation you may do like this: $act->getDeplacement and foreach deplacement set act.
    – Stoads
    Jul 14, 2019 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.