Map ORM model to foreign database table - php

This is a follow-up question to this one.
In my Typo3 plugin I have a model:
<?php
namespace Homeinfo\SysMon2\Domain\Model;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
class CheckResults extends AbstractEntity
{
/**
* #var int $id
*/
public $id;
/**
* #var DateTime $timestamp
*/
public $timestamp;
/**
* #var int $system
*/
public $system;
/**
* #var bool $icmp_request
*/
public $icmp_request;
/**
* #var string $ssh_login
*/
public $ssh_login ;
/**
* #var string $http_request
*/
public $http_request;
/**
* #var string $application_state
*/
public $application_state;
/**
* #var string $smart_check
*/
public $smart_check;
/**
* #var string $baytrail_freeze
*/
public $baytrail_freeze;
/**
* #var string $fsck_repair
*/
public $fsck_repair;
/**
* #var bool $application_version
*/
public $application_version;
/**
* #var int $ram_total
*/
public $ram_total;
/**
* #var int $ram_free
*/
public $ram_free;
/**
* #var int $ram_available
*/
public $ram_available;
/**
* #var string $efi_mount_ok
*/
public $efi_mount_ok;
/**
* #var int $download
*/
public $download;
/**
* #var int $upload
*/
public $upload;
/**
* #var string $root_not_ro
*/
public $root_not_ro;
/**
* #var string $sensors
*/
public $sensors;
/**
* #var bool $in_sync
*/
public $in_sync;
/**
* #var int $recent_touch_events
*/
public $recent_touch_events;
/**
* #var DateTime $offline_since
*/
public $offline_since;
/**
* #var DateTime $blackscreen_since
*/
public $blackscreen_since;
}
Which represents a table of a foreign database.
I configured that database via:
'Default' => [
...
],
'Sysmon' => [
'charset' => 'utf8mb4',
'dbname' => 'sysmon',
'driver' => 'mysqli',
'host' => 'REDACTED',
'password' => 'REDACTED',
'port' => 3306,
'tableoptions' => [
'charset' => 'utf8mb4',
'collate' => 'utf8mb4_general_ci',
],
'user' => 'sysmon_ro',
],
],
'TableMapping' => [
'checkresults' => 'Sysmon',
'offlinehistory' => 'Sysmon',
],
How do I let Typo3 know, that the 'checkresults' => 'Sysmon' mapping should use the aforementioned model class?
The official documentation does not mention how to do this.

Related

Symfony 3 - Form with OneToMany association in database

I work on a OneToMany association in my database. This association work perfectly when I try to add data from fixtures and when I try to return data from database.
The problem is with my FormType CommandType which does'nt work. Symfony and Doctrine return this error message :
An exception occurred while executing 'INSERT INTO command_product (quantity, command_id, product_id) VALUES (?, ?, ?)' with params [3, null, 1]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'command_id' cannot be null
CommandType's code :
class CommandType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('establishment', EntityType::class, array(
'class' => Company::class,
'required' => true
))
->add('dateCreation', DateTimeType::class, array(
'widget' => 'single_text',
'format' => 'yyyy-MM-dd',
'required' => true
))
->add('contains', CollectionType::class, array(
'entry_type' => CommandProductType::class,
'required' => true,
'allow_add' => true
))
->add('state',TextType::class, array(
'required' => true
))
->add('totalAmount', MoneyType::class, array(
'required' => true
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Command::class
));
}
public function getBlockPrefix()
{
return 'appbundle_command';
}
}
CommandProductType's code :
class CommandProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('quantity', NumberType::class, array(
'required' => true
))
->add('product', EntityType::class, array(
'class' => Product::class,
'required' => true
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => CommandProduct::class
));
}
public function getBlockPrefix()
{
return 'appbundle_commandproduct';
}
}
Command's code class :
class Command
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Company $establishment
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Company")
* #ORM\JoinColumn(name="establishment_id", referencedColumnName="id", nullable=false)
*/
private $establishment;
/**
* #var DateTime $dateCreation
*
* #ORM\Column(name="dateCreation", type="datetime", nullable=false)
* #Assert\Type("datetime")
*/
private $dateCreation;
/**
* #var string $state
*
* #ORM\Column(name="state", type="string", length=255, nullable=false)
* #Assert\Type("string")
*/
private $state;
/**
* #var float $totalAmount
*
* #ORM\Column(name="totalAmount", type="float", precision=10, scale=2, nullable=false)
* #Assert\NotBlank()
* #Assert\Type(type="float")
*/
private $totalAmount;
/**
* #var mixed $contains
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CommandProduct", mappedBy="contain", cascade={"persist", "remove"})
*/
private $contains;
public function __construct()
{
$this->contains = new ArrayCollection();
}
/**
* #var CommandProduct $commandProduct
*/
public function addContain(CommandProduct $commandProduct = null)
{
$commandProduct->setContain($this);
$this->contains->add($commandProduct);
}
/**
* #param CommandProduct $commandProduct
*/
public function removeContain(CommandProduct $commandProduct)
{
if ($this->contains->contains($commandProduct)) {
$this->contains->removeElement($commandProduct);
}
}
}
CommandOrder's code class :
class CommandProduct
{
/**
* #var int $id
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var Command $contain
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Command", inversedBy="contains")
* #ORM\JoinColumn(name="command_id", referencedColumnName="id", nullable=false)
*/
private $contain;
/**
* #var int $quantity
*
* #ORM\Column(name="quantity", type="integer", nullable=true, options={"default": 1})
* #Assert\NotBlank()
* #Assert\Type(type="int")
*/
private $quantity;
/**
* #var Product $product
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Product")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $product;
}

Laravel doctrine only returning single attribute from findAll() query

Im using laravel doctrine in a lumen application, in one of my controllers i have an index function that should return all records from a given entity.
the function looks like this
public function index(ServerRequestInterface $request)
{
return $this->showResponse(app()->make('em')->getRepository('App\Entities\showOff')->findAll());
}
which returns data like this
[
{
"nodeType": 'showOff'
},
{
"nodeType": 'showOff'
},
{
"nodeType": 'showOff'
},
{
"nodeType": 'showOff'
}
]
This is only one attribute in the entity.
If i turn the doctrine debugger on is see the executed SQL query like
SELECT t0.type AS type_1, t0.size AS size_2, t0.last_modified AS last_modified_3, t0.hair_cutter AS hair_cutter_4, t0.file_path AS file_path_5, t0.content_url AS content_url_6, t0.embed_url AS embed_url_7, t0.height AS height_8, t0.width AS width_9, t0.player_type AS player_type_10, t0.about AS about_11, t0.award AS award_12, t0.comment AS comment_13, t0.comment_count AS comment_count_14, t0.text AS text_15, t0.thumbnail AS thumbnail_16, t0.version AS version_17, t0.name AS name_18, t0.id AS id_19, t0.nid AS nid_20, t0.node_type AS node_type_21, t0.owner_id AS owner_id_22, t23.enabled AS enabled_24, t23.username AS username_25, t23.email AS email_26, t23.password AS password_27, t23.remember_token AS remember_token_28, t23.name AS name_29, t23.id AS id_30, t23.nid AS nid_31, t23.node_type AS node_type_32, t0.aggregate_rating_id AS aggregate_rating_id_33, t34.rating_count AS rating_count_35, t34.rating_score AS rating_score_36, t34.name AS name_37, t34.id AS id_38, t34.nid AS nid_39, t34.node_type AS node_type_40, t0.author_id AS author_id_41, t42.enabled AS enabled_43, t42.username AS username_44, t42.email AS email_45, t42.password AS password_46, t42.remember_token AS remember_token_47, t42.name AS name_48, t42.id AS id_49, t42.nid AS nid_50, t42.node_type AS node_type_51, t0.translator_id AS translator_id_52, t53.enabled AS enabled_54, t53.username AS username_55, t53.email AS email_56, t53.password AS password_57, t53.remember_token AS remember_token_58, t53.name AS name_59, t53.id AS id_60, t53.nid AS nid_61, t53.node_type AS node_type_62 FROM show_off t0 LEFT JOIN users t23 ON t0.owner_id = t23.id LEFT JOIN aggregate_rating t34 ON t0.aggregate_rating_id = t34.id LEFT JOIN users t42 ON t0.author_id = t42.id LEFT JOIN users t53 ON t0.translator_id = t53.id ;
when ran from the mysql command line it returns all data as it should.
Some where along the line all my attributes are being stripped out.
my entity looks like so
<?php
namespace App\Entities;
use Doctrine\ORM\Mapping as ORM;
use App\Jobs\IndexNewEntitiesJob;
use App\Jobs\UpdateIndexEntitiesJob;
use Doctrine\Common\Collections\ArrayCollection;
use ApiArchitect\Compass\Entities\User;
/**
* Class ShowOff
*
* #package Jkirkby91\DoctrineSchemas
* #author James Kirkby <jkirkby91#gmail.com>
*
* #ORM\Entity
* #ORM\HasLifeCycleCallbacks
* #ORM\Table(name="show_off")
* #ORM\Entity(repositoryClass="App\Repositories\ShowOffRepository")
*/
class ShowOff extends \App\Entities\MediaObject
{
/**
* #ORM\Column(type="string", length=45, nullable=false, unique=false)
*/
protected $type;
/**
* #ORM\Column(type="integer", length=45, nullable=false)
*/
protected $size;
/**
* #ORM\Column(type="datetime", length=45, nullable=false, unique=false)
*/
protected $lastModified;
/**
* #ORM\OneToOne(targetEntity="\ApiArchitect\Compass\Entities\User", fetch="EAGER", cascade={"persist"})
*/
protected $owner;
/**
* #ORM\OneToOne(targetEntity="\App\Entities\HairCutter", fetch="EAGER", cascade={"persist"})
* #ORM\Column(nullable=true, unique=false)
*/
protected $hairCutter;
/**
* #ORM\Column(type="string", length=255, nullable=false)
*/
protected $filePath;
/**
* HairCutter constructor.
* #param $fileName
* #param $filePath
* #param $owner
* #param $hairCutter
*/
public function __construct($fileName, $filePath, User $owner, $type, $lastModified, $size)
{
$this->name = $fileName;
$this->filePath = $filePath;
$this->owner = $owner;
$this->type = $type;
$this->lastModified = $lastModified;
$this->size = $size;
$this->nodeType = 'showOff';
}
/**
* Gets the value of filePath.
*
* #return mixed
*/
public function getFilePath()
{
return $this->filePath;
}
/**
* Sets the value of filePath.
*
* #param mixed $filePath the file path
*
* #return self
*/
protected function setFilePath($filePath)
{
$this->filePath = $filePath;
return $this;
}
/**
* Gets the value of owner.
*
* #return mixed
*/
public function getOwner()
{
return $this->owner;
}
/**
* Sets the value of owner.
*
* #param mixed $owner the owner
*
* #return self
*/
protected function setOwner(User $owner)
{
$this->owner = $owner;
return $this;
}
/**
* Gets the value of hairCutter.
*
* #return mixed
*/
public function getHairCutter()
{
return $this->hairCutter;
}
/**
* Sets the value of hairCutter.
*
* #param mixed $hairCutter the hair cutter
*
* #return self
*/
protected function setHairCutter($hairCutter)
{
$this->hairCutter = $hairCutter;
return $this;
}
}
my config looks like so
<?php
return [
'managers' => [
'default' => [
'dev' => env('APP_DEBUG'),
'meta' => env('DOCTRINE_METADATA', 'annotations'),
'connection' => env('DB_CONNECTION', 'sqlite'),
'namespaces' => [
'app'
],
'paths' => [
env('COMPASS_ENTITIES',base_path('vendor/apiarchitect/compass/src/Entities')),
env('AUTH_ENTITIES',base_path('vendor/apiarchitect/auth/src/Entities')),
env('LOG_ENTITIES',base_path('vendor/apiarchitect/log/src/Entities')),
env('NODE_ENTITIES',base_path('vendor/jkirkby91/lumendoctrinecomponent/src/Entities')),
env('APP_ENTITIES',base_path('/app/Entities')),
],
'repository' => Doctrine\ORM\EntityRepository::class,
'proxies' => [
'namespace' => false,
'path' => storage_path('proxies'),
'auto_generate' => env('DOCTRINE_PROXY_AUTOGENERATE', false)
],
'events' => [
'listeners' => [],
'subscribers' => []
],
'filters' => [],
'mapping_types' => [
'enum' => 'string'
]
]
],
'extensions' => [
LaravelDoctrine\Extensions\Timestamps\TimestampableExtension::class,
LaravelDoctrine\Extensions\SoftDeletes\SoftDeleteableExtension::class,
LaravelDoctrine\Extensions\Loggable\LoggableExtension::class,
LaravelDoctrine\Extensions\Blameable\BlameableExtension::class,
LaravelDoctrine\Extensions\IpTraceable\IpTraceableExtension::class,
LaravelDoctrine\ORM\Extensions\TablePrefix\TablePrefixExtension::class,
'custom_types' => [
'json' => LaravelDoctrine\ORM\Types\Json::class
],
'custom_datetime_functions' => [],
'custom_numeric_functions' => [],
'custom_string_functions' => [],
'logger' => env('DOCTRINE_LOGGER', trrue),
'cache' => [
'default' => env('DOCTRINE_CACHE', 'memcached'),
'namespace' => null,
'second_level' => false,
],
'gedmo' => [
'all_mappings' => false
],
'doctrine_presence_verifier' => true,
];
Does any one know why this is doing this?
You write in your question:
Some where along the line all my attributes are being stripped out.
I suspect something happens with the data inside the showResponse method that you wrap around the result set that is returned from the repository findAll() call.
Try once to separate the result from the showResponse call and check what you get then:
public function index(ServerRequestInterface $request)
{
$result = app()->make('em')->getRepository('App\Entities\ShowOff')->findAll();
var_dump( $result ); // <-- should contain a collection of ShowOff entities.
return $this->showResponse($result); // <-- something happens and returns an array
}

Unique validation of two fields from different tables in Yii2

I have three models related in Yii2, with attributes:
AyudanteSituacionLaboral (ID, FechaInicio, State, Ayudante_ID)
Ayudante(ID, Name )
HRutaDistribucion (ID, Fecha, Ayudante_ID)
I need to check uniqueness of Fecha and Ayudante_ID against AyudanteSituacionLaboral=>FechaInicio and AyudanteSituacionLaboral=>Ayudante_ID respectively. So when I choose from HRutaDistribucion form an Ayudante instance that already has an entry in AyudanteSituacionLaboral with Fecha like FechaInicio field, it launches an error message.
Here's HRutaDistribucion Model:
<?php
namespace backend\models;
use backend\controllers\AyudanteSituacionLaboralController;
use Yii;
/**
* This is the model class for table "hruta_distribucion".
*
* #property integer $HRuta_ID
* #property integer $Carro_DistribucionCarroID
* #property integer $ChoferChofer_ID
* #property integer $AyudanteAyudante_ID
* #property integer $HojaRuta
* #property string $Fecha
* #property string $FechaEmision
* #property integer $Capacidad_Transportada
*
* #property Ayudante $ayudanteAyudante
* #property CarroDistribucion $carroDistribucionCarro
* #property Chofer $choferChofer
* #property ViajeDistribucion[] $viajeDistribucions
*/
class HrutaDistribucion extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'hruta_distribucion';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
// [[ 'HojaRuta', 'Fecha', 'FechaEmision'], 'required'],
[['Fecha', 'FechaEmision','Carro_DistribucionCarroID', 'ChoferChofer_ID', 'AyudanteAyudante_ID', 'HojaRuta','Capacidad_Transportada'], 'safe', 'on'=>'search'],
['Fecha', 'unique', 'message' => ("Este trabajador ya esta en esta fecha")]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'HRuta_ID' => 'Hruta ID',
'Carro_DistribucionCarroID' => 'Carro Distribucion Carro ID',
'ChoferChofer_ID' => 'Chofer Chofer ID',
'AyudanteAyudante_ID' => 'Ayudante Ayudante ID',
'HojaRuta' => 'Hoja Ruta',
'Fecha' => 'Fecha',
'FechaEmision' => 'Fecha Emision',
'Capacidad_Transportada' => 'Capacidad Transportada',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAyudanteAyudante()
{
return $this->hasOne(Ayudante::className(), ['Ayudante_ID' => 'AyudanteAyudante_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCarroDistribucionCarro()
{
return $this->hasOne(CarroDistribucion::className(), ['CarroDistID' => 'Carro_DistribucionCarroID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getChoferChofer()
{
return $this->hasOne(Chofer::className(), ['Chofer_ID' => 'ChoferChofer_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getViajeDistribucions()
{
return $this->hasMany(ViajeDistribucion::className(), ['HRuta_DistribucionHRuta_ID' => 'HRuta_ID']);
}
}
Here's AyudanteSituacionLaboral Model:
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "ayudante_situacion_laboral".
*
* #property integer $AyudanteAyudante_ID
* #property integer $Situacion_LaboralSitL_ID
* #property string $Fecha
* #property integer $Cant_Dias
* #property integer $Cant_Horas
* #property string $Descripcion
* #property string $Fecha_Creacion
*
* #property Ayudante $ayudanteAyudante
* #property SituacionLaboral $situacionLaboralSitL
*/
class AyudanteSituacionLaboral extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'ayudante_situacion_laboral';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['AyudanteAyudante_ID', 'Situacion_LaboralSitL_ID', 'Fecha_Creacion'], 'required'],
[['AyudanteAyudante_ID', 'Situacion_LaboralSitL_ID','FechaInicio','FechaFin', 'Fecha_Creacion','Cant_Horas'], 'safe'],
[['Descripcion'], 'string', 'max' => 255],
['Cant_Horas', 'required', 'when'=>function($model){
return (empty($model->FechaInicio))? true:false;
}, 'whenClient'=>"function(){
if ( $('#FechaInicio').val()=== undefined)
{ false;
}else{
true;}
}" ],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'AyudanteAyudante_ID' => 'Nombre Ayudante',
'Situacion_LaboralSitL_ID' => 'Situación Laboral',
'FechaInicio' => 'Fecha Inicio',
'FechaFin' => 'Fecha Fin',
'Cant_Horas' => 'Cant. Horas',
'Descripcion' => 'Observ.',
'Fecha_Creacion' => 'Fecha Creacion',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAyudanteAyudante()
{
return $this->hasOne(Ayudante::className(), ['Ayudante_ID' => 'AyudanteAyudante_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSituacionLaboralSitL()
{
return $this->hasOne(SituacionLaboral::className(), ['SitL_ID' => 'Situacion_LaboralSitL_ID']);
}
}
And finally Ayudante Model:
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "ayudante".
*
* #property integer $Ayudante_ID
* #property integer $Registro
* #property string $Nombre
*
* #property AyudanteSituacionLaboral[] $ayudanteSituacionLaborals
* #property SituacionLaboral[] $situacionLaboralSitLs
* #property ViajeDistribucion[] $viajeDistribucions
* #property ViajeGlp[] $viajeGlps
*/
class Ayudante extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'ayudante';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['Registro','Nombre'],'required'],
[['Registro'], 'integer'],
[['CI'], 'string', 'max' => 11],
[['Nombre'], 'string', 'max' => 50]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'Ayudante_ID' => 'ID',
'Registro' => 'Registro',
'CI'=>'CI',
'Nombre' => 'Nombre',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAyudanteSituacionLaborals()
{
return $this->hasMany(AyudanteSituacionLaboral::className(), ['AyudanteAyudante_ID' => 'Ayudante_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSituacionLaboralSitLs()
{
return $this->hasMany(SituacionLaboral::className(), ['SitL_ID' => 'Situacion_LaboralSitL_ID'])->viaTable('ayudante_situacion_laboral', ['AyudanteAyudante_ID' => 'Ayudante_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getViajeDistribucions()
{
return $this->hasMany(ViajeDistribucion::className(), ['AyudanteAyudante_ID' => 'Ayudante_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getViajeGlps()
{
return $this->hasMany(ViajeGlp::className(), ['AyudanteAyudante_ID' => 'Ayudante_ID']);
}
}
Could be you need exist validator
http://www.yiiframework.com/doc-2.0/yii-validators-existvalidator.html
In your HRutaDistribucion model you should add this to your rules
[['Date', 'Ayudante_ID '], 'exist',
'targetClass' => AyudanteSituacionLaboral::ClassName() ,
'targetAttribute' => ['Date', 'Ayudante_ID ']]

Property not found Symfony

I'm receiving this error on Symfony 2.7.9:
Neither the property "puestos" nor one of the methods "addPuesto()"/"removePuesto()", "setPuestos()", "puestos()", "__set()" or "__call()" exist and have public access in class "UserBundle\Entity\UsuarioTrabajador".
<?php
namespace UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use PUGX\MultiUserBundle\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity
* #ORM\Table(name="usuario_trabajador")
* #UniqueEntity(fields = "username", targetClass = "UserBundle\Entity\Usuario", message="fos_user.username.already_used")
* #UniqueEntity(fields = "email", targetClass = "UserBundle\Entity\Usuario", message="fos_user.email.already_used")
*
* #UniqueEntity(fields = {"nit","dpi"}, targetClass = "UserBundle\Entity\UsuarioTrabajador", message="El dpi o nit debe ser único")
* Esta entidad cubre los tipos de Asistente, Supervisor y Gerente.
*
* #author Pablo Díaz soporte#newtonlabs.com.gt
*/
class UsuarioTrabajador extends Usuario
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="direccion",type="string",length=255)
*/
private $direccion;
/**
* #var date fecha de egreso de la empresa.
* #ORM\Column(name="fechaEgreso", type="date",nullable=true)
*/
private $fechaEgreso;
/**
* #var string DPI del trabajador
* #ORM\Column(name="dpi",type="string",length=20, unique=true)
*/
private $dpi;
/**
* Número de identificación tributaria.
*
* #var string
* #ORM\Column(name="nit", type="string",length=20,unique=true)
*/
private $nit;
/**
* #var int
* #ORM\Column(name="telefono", type="string",length=15,nullable=true)
*/
private $telefono;
/**
* #var ArrayCollection
* #ORM\OneToMany(targetEntity="DatosPrestaciones", mappedBy="usuario")
*/
private $datosPrestaciones;
/**
* #var string Tipo de Usuarios(Asistente, Supervisor, Gerente)
* #ORM\OneToMany(targetEntity="UserBundle\Entity\Puesto", mappedBy="usuarioPuesto")
*/
private $puestos;
/**
* Constructor.
*/
public function __construct()
{
$this->datosPrestaciones = new \Doctrine\Common\Collections\ArrayCollection();
$this->puestos = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set direccion
*
* #param string $direccion
*
* #return UsuarioTrabajador
*/
public function setDireccion($direccion)
{
$this->direccion = $direccion;
return $this;
}
/**
* Get direccion
*
* #return string
*/
public function getDireccion()
{
return $this->direccion;
}
/**
* Set fechaEgreso
*
* #param \DateTime $fechaEgreso
*
* #return UsuarioTrabajador
*/
public function setFechaEgreso($fechaEgreso)
{
$this->fechaEgreso = $fechaEgreso;
return $this;
}
/**
* Get fechaEgreso
*
* #return \DateTime
*/
public function getFechaEgreso()
{
return $this->fechaEgreso;
}
/**
* Set dpi
*
* #param string $dpi
*
* #return UsuarioTrabajador
*/
public function setDpi($dpi)
{
$this->dpi = $dpi;
return $this;
}
/**
* Get dpi
*
* #return string
*/
public function getDpi()
{
return $this->dpi;
}
/**
* Set nit
*
* #param string $nit
*
* #return UsuarioTrabajador
*/
public function setNit($nit)
{
$this->nit = $nit;
return $this;
}
/**
* Get nit
*
* #return string
*/
public function getNit()
{
return $this->nit;
}
/**
* Set telefono
*
* #param string $telefono
*
* #return UsuarioTrabajador
*/
public function setTelefono($telefono)
{
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* #return string
*/
public function getTelefono()
{
return $this->telefono;
}
/**
* Add datosPrestacione
*
* #param \UserBundle\Entity\DatosPrestaciones $datosPrestacione
*
* #return UsuarioTrabajador
*/
public function addDatosPrestacione(\UserBundle\Entity\DatosPrestaciones $datosPrestacione)
{
$this->datosPrestaciones[] = $datosPrestacione;
return $this;
}
/**
* Remove datosPrestacione
*
* #param \UserBundle\Entity\DatosPrestaciones $datosPrestacione
*/
public function removeDatosPrestacione(\UserBundle\Entity\DatosPrestaciones $datosPrestacione)
{
$this->datosPrestaciones->removeElement($datosPrestacione);
}
/**
* Get datosPrestaciones
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDatosPrestaciones()
{
return $this->datosPrestaciones;
}
/**
* Add puesto
*
* #param \UserBundle\Entity\Puesto $puesto
*
* #return UsuarioTrabajador
*/
public function addPuesto(\UserBundle\Entity\Puesto $puesto)
{
$this->puestos[] = $puesto;
return $this;
}
/**
* Remove puesto
*
* #param \UserBundle\Entity\Puesto $puesto
*/
public function removePuesto(\UserBundle\Entity\Puesto $puesto)
{
$this->puestos->removeElement($puesto);
}
/**
* Get puestos
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPuestos()
{
return $this->puestos;
}
public function __toString()
{
return $this->nombre.' '.$this->apellidos;
}
}
This is the other Entity
<?php
namespace UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Puesto
*
* #ORM\Table()
* #ORM\Entity
*/
class Puesto
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="tipoPuesto",type="string",length=100)
*/
private $tipoPuesto;
/**
* #var string
*
* #ORM\Column(name="nombrePuesto", type="string", length=255)
*/
private $nombrePuesto;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\UsuarioTrabajador", inversedBy="puestos")
* #var [type]
*/
private $usuarioPuesto;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombrePuesto
*
* #param string $nombrePuesto
*
* #return Puesto
*/
public function setNombrePuesto($nombrePuesto)
{
$this->nombrePuesto = $nombrePuesto;
return $this;
}
/**
* Get nombrePuesto
*
* #return string
*/
public function getNombrePuesto()
{
return $this->nombrePuesto;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return Puesto
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set usuario
*
* #param \UserBundle\Entity\UsuarioTrabajdor $usuario
*
* #return Puesto
*/
public function setUsuario(\UserBundle\Entity\UsuarioTrabajdor $usuario = null)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return \UserBundle\Entity\UsuarioTrabajdor
*/
public function getUsuario()
{
return $this->usuario;
}
/**
* Set tipoPuesto
*
* #param string $tipoPuesto
*
* #return Puesto
*/
public function setTipoPuesto($tipoPuesto)
{
$this->tipoPuesto = $tipoPuesto;
return $this;
}
/**
* Get tipoPuesto
*
* #return string
*/
public function getTipoPuesto()
{
return $this->tipoPuesto;
}
/**
* Mostrar el noombre del puesto
* #return string
*/
public function __toString()
{
return $this->tipoPuesto.': '.$this->nombrePuesto.' '.$this->getUsuarioPuesto();
}
/**
* Set usuarioPuesto
*
* #param \UserBundle\Entity\UsuarioTrabajador $usuarioPuesto
*
* #return Puesto
*/
public function setUsuarioPuesto(\UserBundle\Entity\UsuarioTrabajador $usuarioPuesto = null)
{
$this->usuarioPuesto = $usuarioPuesto;
return $this;
}
/**
* Get usuarioPuesto
*
* #return \UserBundle\Entity\UsuarioTrabajador
*/
public function getUsuarioPuesto()
{
return $this->usuarioPuesto;
}
}
This is the Form
<?php
namespace UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class RegistrationTrabajadorFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// agregar campos personalizados
$builder->add('nombre', null, [
'label' => 'Nombre/s',
'attr' => [
'placeholder' => 'Nombre/s',
'class' => 'form-control input-lg',
],
])
->add('apellidos', null, [
'label' => 'Apellidos/s',
'attr' => [
'placeholder' => 'Apellidos',
'class' => 'form-control input-lg',
],
])
->add('username', null, [
'label' => 'Usuario',
'translation_domain' => 'FOSUserBundle',
'attr' => [
'class' => 'form-control input-lg',
'placeholder' => 'Nombre de Usuario',
],
])
->add('email', 'email', [
'label' => 'Correo',
'translation_domain' => 'FOSUserBundle',
'required' => true,
'attr' => [
'class' => 'form-control input-lg',
'placeholder' => 'Correo electrónico',
],
])
->add('plainPassword', 'repeated', [
'label' => 'Contraseña',
'type' => 'password',
'options' => ['translation_domain' => 'FOSUserBundle'],
'first_options' => [
'label' => 'Contraseña',
'attr' => [
'class' => 'form-control input-lg',
'placeholder' => 'Contraseña',
],
],
'second_options' => [
'label' => 'Repetir Contraseña',
'attr' => [
'class' => 'form-control input-lg',
'placeholder' => 'Repetir Contraseña',
],
],
'invalid_message' => 'fos_user.password.mismatch',
])
->add('direccion',null,[
'label' => 'Dirección',
'attr' => [
'class' => 'form-control input-lg',
'placeholder' => 'Dirección',
],
'required' => true,
])
->add('dpi', null, [
'label' => 'DPI',
'attr' => [
'class' => 'form-control input-lg',
'placeholder' => 'Documento Personal de Identificación',
],
'required' => true,
])
->add('nit', null, [
'label' => 'NIT',
'attr' => [
'class' => 'form-control input-lg',
'placeholder' => 'Número de Identificación Tributaria',
],
'required' => true,
])
->add('telefono', null, [
'label' => 'Teléfono',
'translation_domain' => 'FOSUserBundle',
'attr' => [
'class' => 'form-control input-lg',
'placeholder' => 'Teléfono',
],
'required' => false,
])
->add('submit', 'submit', [
'label' => 'Guardar',
'attr' => [
'class' => 'btn btn-primary',
],
])
->add('puestos', 'entity', [
'label' => false,
'empty_value' => 'Aquí aparecerá su puesto',
'class' => 'UserBundle:Puesto',
'attr' => [
'class' => 'select2',
],
])
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'validation' => ['registration'],
]);
}
public function getParent()
{
return 'fos_user_registration';
}
public function getName()
{
return 'user_registration';
}
}

Symfony2 Subform collection with filtered entity erase current entity

sorry for my english i'm french ! I'll try to explain my problem...
Context
I want to create matchs reports for a football game, each captain can add or delete players of his own team with stats (goals, assists, etc...).
Problem
Everything is working for one captain, I can add/delete players successfully recorded in database with only players of the team of the current captain. But, when the other want to do this, the subform show stats i've recorded previously but with the name of the team... And if I validate, the line in database is overridden with the name of the new player.
Example: I enter the result with my player "Player1" who scored twice ! When I save, everything gone perfectly saved in database.
When I want to do the same as the second captain, with my player "Player2" who scores 1 goal. The line previously saved is overriden by the data of player2...
Code
Here is my code
Controller simplified
$em = $this->getDoctrine()->getManager();
$match = $em->getRepository('OCPlatformBundle:Matchs')->findOneById($id);
$form = $this->get('form.factory')->create(new MatchType(), $match);
$form->handleRequest($request);
//VERIF FEUILLE DE MATCH
foreach($match->getStatsplayer() as $player){
$player->setDefcleansheet(false);
$player->setGkcleansheet(false);
$player->setGame($match);
$player->setClub($user->getClub());
}
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($match);
$em->flush();
MatchType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('homescore', 'choice', array('choices' => array(0,1,2,3,4,5,6,7,8,9,10,11,12)))
->add('awayscore', 'choice', array('choices' => array(0,1,2,3,4,5,6,7,8,9,10,11,12)))
->add('statsplayer', 'collection', array(
'type' => new StatsType(),
'allow_add' => true,
'allow_delete' => true))
->add('save', 'submit')
;
}
StatsType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
//Players to show is filtered with the querybuilder
$builder
->add('player', 'entity', array(
'class' => 'OCUserBundle:User',
'property' => 'username',
'query_builder' => function(\Doctrine\ORM\EntityRepository $er) {
global $kernel;
$user = $kernel->getContainer()->get('security.context')->getToken()->getUser();
return $er->createQueryBuilder('q')
->where('q.club = :pf')
->orderBy('q.club', 'ASC')
->setParameter('pf', $user->getClub());
},
'required' => true,
'label' => false,
))
->add('goals', 'choice', array(
'choices' => array(0,1,2,3,4,5,6,7),
'label' => 'goals', 'translation_domain' => 'FOSUserBundle', 'attr' => array(
'placeholder' => 'goals'
)))
->add('assists', 'choice', array(
'choices' => array(0,1,2,3,4,5,6,7),
'label' => 'assists', 'translation_domain' => 'FOSUserBundle', 'attr' => array(
'placeholder' => 'assists'
)))
}
Thanks for your help !
EDIT:
My entities :
Matchs.php
/**
* Matchs
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="OC\PlatformBundle\Entity\MatchsRepository")
*/
class Matchs
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="competition", type="integer")
*/
private $competition;
/**
* #var integer
*
* #ORM\Column(name="phase", type="integer")
*/
private $phase;
/**
* #var \DateTime
*
* #ORM\Column(name="datemax", type="datetime")
*/
private $datemax;
/**
* #ORM\ManyToOne(targetEntity="OC\PlatformBundle\Entity\Club")
* #ORM\Joincolumn(nullable=false)
*/
private $home;
/**
* #ORM\ManyToOne(targetEntity="OC\PlatformBundle\Entity\Club")
* #ORM\Joincolumn(nullable=false)
*/
private $away;
/**
* #var integer
*
* #ORM\Column(name="homescore", type="integer")
*/
private $homescore;
/**
* #var integer
*
* #ORM\Column(name="awayscore", type="integer")
*/
private $awayscore;
/**
* #var \DateTime
*
* #ORM\Column(name="dateevent", type="datetime")
*/
private $dateevent;
/**
* #ORM\OneToMany(targetEntity="OC\PlatformBundle\Entity\Stats", mappedBy="game", cascade={"persist"})
* #Assert\Valid
*/
private $statsplayer;
Stats.php
/**
* Stats
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="OC\PlatformBundle\Entity\StatsRepository")
* #UniqueEntity({"player","game"})
*/
class Stats
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="OC\UserBundle\Entity\User", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $player;
/**
* #ORM\ManyToOne(targetEntity="OC\PlatformBundle\Entity\Club")
* #ORM\JoinColumn(nullable=false)
*/
private $club;
/**
* #ORM\ManyToOne(targetEntity="OC\PlatformBundle\Entity\Matchs", inversedBy="statsplayer", cascade={"persist"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="game_id", referencedColumnName="id")
* })
*/
private $game;
/**
* #var integer
*
* #ORM\Column(name="goals", type="integer")
*/
private $goals;
/**
* #var integer
*
* #ORM\Column(name="assists", type="integer")
*/
private $assists;
/**
* #var boolean
*
* #ORM\Column(name="yellowcard", type="boolean")
*/
private $yellowcard;
/**
* #var boolean
*
* #ORM\Column(name="redcard", type="boolean")
*/
private $redcard;
/**
* #var boolean
*
* #ORM\Column(name="defcleansheet", type="boolean")
*/
private $defcleansheet;
/**
* #var boolean
*
* #ORM\Column(name="gkcleansheet", type="boolean")
*/
private $gkcleansheet;

Categories