I created a xsd and used it with jaxb plugin like bellow:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.mycompany.fr/Canonical/Schema/invoices.xsd"
targetNamespace="http://www.mycompany.fr/Canonical/Schema/invoices.xsd"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:element name="invoices">
<xs:complexType>
<xs:sequence>
<xs:element name="invoice" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="invoice-type" type="xs:string"/>
<xs:element minOccurs="0" name="insertion-date" type="xs:dateTime"/>
<xs:element minOccurs="0" name="amount" type="xs:double"/>
</xs:sequence>
<xs:attribute name="invoice-number" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.5.0</version>
<executions>
<execution>
<id>xsd-to-java</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<packageName>com.mycompany.model</packageName>
<sources>
<source>src/main/resources/xsd/invoices.xsd</source>
</sources>
</configuration>
</plugin>
It generated me this class:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"invoice"
})
#XmlRootElement(name = "invoices")
public class Invoices {
protected List<Invoice> invoice;
/**
* Gets the value of the invoice property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the invoice property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getInvoice().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {#link Invoice }
*
*
*/
public List<Invoice> getInvoice() {
if (invoice == null) {
invoice = new ArrayList<Invoice>();
}
return this.invoice;
}
/**
* <p>Classe Java pour anonymous complex type.
*
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="invoice-type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="insertion-date" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="amount" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
* </sequence>
* <attribute name="invoice-number" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"invoiceType",
"insertionDate",
"amount"
})
public static class Invoice {
#XmlElement(name = "invoice-type")
protected String invoiceType;
#XmlElement(name = "insertion-date")
#XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar insertionDate;
protected Double amount;
#XmlAttribute(name = "invoice-number", required = true)
protected String invoiceNumber;
/**
* Obtient la valeur de la propriété invoiceType.
*
* #return
* possible object is
* {#link String }
*
*/
public String getInvoiceType() {
return invoiceType;
}
/**
* Définit la valeur de la propriété invoiceType.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setInvoiceType(String value) {
this.invoiceType = value;
}
/**
* Obtient la valeur de la propriété insertionDate.
*
* #return
* possible object is
* {#link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getInsertionDate() {
return insertionDate;
}
/**
* Définit la valeur de la propriété insertionDate.
*
* #param value
* allowed object is
* {#link XMLGregorianCalendar }
*
*/
public void setInsertionDate(XMLGregorianCalendar value) {
this.insertionDate = value;
}
/**
* Obtient la valeur de la propriété amount.
*
* #return
* possible object is
* {#link Double }
*
*/
public Double getAmount() {
return amount;
}
/**
* Définit la valeur de la propriété amount.
*
* #param value
* allowed object is
* {#link Double }
*
*/
public void setAmount(Double value) {
this.amount = value;
}
/**
* Obtient la valeur de la propriété invoiceNumber.
*
* #return
* possible object is
* {#link String }
*
*/
public String getInvoiceNumber() {
return invoiceNumber;
}
/**
* Définit la valeur de la propriété invoiceNumber.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setInvoiceNumber(String value) {
this.invoiceNumber = value;
}
}
}
And I used this Camel route to unmasharl the xml:
JaxbDataFormat jaxbDataFormat = new JaxbDataFormat();
jaxbDataFormat.setSchema("classpath:xsd/invoices.xsd");
from("file:{{xml.location}}?delay=1000")
.log("Reading invoice XML data from ${header.CamelFileName}")
.unmarshal(jaxbDataFormat)
.split(body())
.to("direct:processedXml");
but when I run my application, I got the following error ...
[route2 ] [unmarshal1 ]
[unmarshal[org.apache.camel.model.dataformat.JaxbDataFormat#7aff8796]
] [ 0]
Stacktrace
--------------------------------------------------------------------------------------------------------------------------------------- : java.io.IOException: javax.xml.bind.UnmarshalException
with linked exception: [com.sun.istack.SAXParseException2; lineNumber: 2; columnNumber: 72; élément inattendu (URI :
"http://www.mycompany.fr/Canonical/Schema/invoices.xsd", local :
"invoices"). Les éléments attendus sont (none)] at
org.apache.camel.converter.jaxb.JaxbDataFormat.unmarshal(JaxbDataFormat.java:312)
at
org.apache.camel.support.processor.UnmarshalProcessor.process(UnmarshalProcessor.java:64)
at
org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:471)
at
org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:187)
at
org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:64)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:184) at
org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:398)
at
org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:492)
at
org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:245)
at
org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:206)
at
org.apache.camel.support.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:202)
at
org.apache.camel.support.ScheduledPollConsumer.run(ScheduledPollConsumer.java:116)
at
java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at
java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
at
java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829) Caused by:
javax.xml.bind.UnmarshalException
Do you know the problem plz ?
Thank a lot and best regards
When unmarshalling, you do not need to refer to a schema, but to a JAXB contextPath. You have to tell JAXB where (=in which packages) to find annotated pojos so that it will be able to turn xml into corresponding java objects.
So try this:
JaxbDataFormat jaxbDataFormat = new JaxbDataFormat();
jaxbDataFormat.setContextPath("com.mycompany.model");
Related
I want to upload an Incidencia to the database and when I try to upload it I get the following error:
Notice: Undefined index: $servicioIdservicio
This field is a foreign key that I take from user that in turn is taking it from services is an id so it is an integer field.
Class Incidencia:
use App\Entity\Usuario;
use App\Entity\Servicio;
/**
* Incidencia
*
* #ORM\Table(name="incidencia", indexes={#ORM\Index(name="Usuario_Servicio_idServicio", columns={"Usuario_Servicio_idServicio"}), #ORM\Index(name="IDX_DF7F4B4C95440347", columns={"Usuario_idUsuario"})})
* #ORM\Entity(repositoryClass="App\Repository\IncidenciaRepository")
*/
class Incidencia
{
/**
* #var int
*
* #ORM\Column(name="idIncidencia", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idincidencia;
/**
* #var string|null
*
* #ORM\Column(name="nombre", type="string", length=128, nullable=true)
*/
private $nombre;
/**
* #var \DateTime|null
*
* #ORM\Column(name="fInicio", type="datetime", nullable=true)
*/
private $finicio;
/**
* #var \DateTime|null
*
* #ORM\Column(name="fFin", type="datetime", nullable=true)
*/
private $ffin;
/**
* #var string|null
*
* #ORM\Column(name="observacion", type="string", length=255, nullable=true)
*/
private $observacion;
/**
* #var string|null
*
* #ORM\Column(name="archivo", type="string", length=255, nullable=true)
*/
private $archivo;
/**
* #var \Usuario
*
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\OneToOne(targetEntity="Usuario")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="Usuario_idUsuario", referencedColumnName="idUsuario")
* })
*/
private $usuarioIdusuario;
/**
* #var \Usuario
*
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\OneToOne(targetEntity="Usuario")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="Usuario_Servicio_idServicio", referencedColumnName="Servicio_idServicio")
* })
*/
private $usuarioServicioIdservicio;
}
I have also tried to change $userServiceServiceIdservice from Usuario to Servicio and the same error comes up
$inc = new Incidencia();
$inc->setNombre($data['incidencia']);
$inc->setFinicio($data['finicio']);
$inc->setFfin($data['ffin']);
$inc->setObservacion($data['observacion']);
if($data['archivo']=!""){
$inc->setArchivo($data['archivo']);
}
$entityManager = $doctrine->getManager();
$user = $entityManager->getRepository(Usuario::class)->find(5);
$inc->setUsuarioIdusuario($user);
$entityManager = $doctrine->getManager();
$serv = $entityManager->getRepository(Servicio::class)->find(2);
$inc->setUsuarioServicioIdservicio($user);
$doctrine->getRepository(Incidencia::class)->addIncidencia($inc);
Method
/**
* #throws ORMException
* #throws OptimisticLockException
*/
public function addIncidencia(Incidencia $entity, bool $flush = true): void
{
$this->_em->persist($entity);
if ($flush) {
$this->_em->flush();
}
}
How can I fix it?
Thank you very much.
Is there a way to handle on entity easily image with sonata media bundle?
I try all solution I find but nothing work....
Many problems :
- unable to delete image from collection
- unable to add more than one file each time
- unable to see thumbnails
This bundle is not easy to use, I think I will rewrite an another bundle I won't spend no more time.
I think I'm doing to the good thing :
<?php
namespace Immo\FichierBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Immeuble
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Immo\FichierBundle\Entity\ImmeubleRepository")
*/
class Immeuble
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="numero", type="integer")
*/
private $numero;
/**
* #var Immo\EtablissementBundle\Entity\Etablissement
*
* #ORM\OneToOne(targetEntity="Immo\EtablissementBundle\Entity\Etablissement", cascade={"persist"})
*/
private $agence;
/**
* #var Immo\FichierBundle\Entity\Adresse
*
* #ORM\OneToOne(targetEntity="Immo\FichierBundle\Entity\Adresse", cascade={"persist"})
*/
private $adresse;
/**
* #var string
*
* #ORM\Column(name="vente", type="string", length=255)
*/
private $vente;
/**
* #var string
*
* #ORM\Column(name="coproindiv", type="string", length=255)
*/
private $coproindiv;
/**
* #var string
*
* #ORM\Column(name="exregulier", type="string", length=255)
*/
private $exregulier;
/**
* #var string
*
* #ORM\OneToMany(targetEntity="Immo\FichierBundle\Entity\ImmeubleHasPhoto", mappedBy="immeuble",cascade={"all"})
* #ORM\OrderBy({"ordre"="ASC"})
*/
private $photos;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function __toString() {
return $this->getNumero().' '.$this->getAdresse();
}
/**
* Constructor
*/
public function __construct()
{
$this->photo = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set numero
*
* #param integer $numero
* #return Immeuble
*/
public function setNumero($numero)
{
$this->numero = $numero;
return $this;
}
/**
* Get numero
*
* #return integer
*/
public function getNumero()
{
return $this->numero;
}
/**
* Set agence
*
* #param Immo\EtablissementBundle\Entity\Etablissement $agence
* #return Immeuble
*/
public function setAgence(\Immo\EtablissementBundle\Entity\Etablissement $agence)
{
$this->agence = $agence;
return $this;
}
/**
* Get agence
*
* #return Immo\EtablissementBundle\Entity\Etablissement
*/
public function getAgence()
{
return $this->agence;
}
/**
* Set adresse
*
* #param Immo\FichierBundle\Entity\Adresse $adresse
* #return Immeuble
*/
public function setAdresse(\Immo\FichierBundle\Entity\Adresse $adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return Immo\FichierBundle\Entity\Adresse
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set vente
*
* #param string $vente
* #return Immeuble
*/
public function setVente($vente)
{
$this->vente = $vente;
return $this;
}
/**
* Get vente
*
* #return string
*/
public function getVente()
{
return $this->vente;
}
/**
* Set coproindiv
*
* #param string $coproindiv
* #return Immeuble
*/
public function setCoproindiv($coproindiv)
{
$this->coproindiv = $coproindiv;
return $this;
}
/**
* Get coproindiv
*
* #return string
*/
public function getCoproindiv()
{
return $this->coproindiv;
}
/**
* Set exregulier
*
* #param string $exregulier
* #return Immeuble
*/
public function setExregulier($exregulier)
{
$this->exregulier = $exregulier;
return $this;
}
/**
* Get exregulier
*
* #return string
*/
public function getExregulier()
{
return $this->exregulier;
}
/**
* Addphoto
*
* #param \Immo\FichierBundle\Entity\ImmeubleHasPhoto $photo
* #return Personne
*/
public function addPhotos(\Immo\FichierBundle\Entity\ImmeubleHasPhoto $photo)
{
$photo->setImmeuble($this);
$this->photos[] = $photo;
return $this;
}
/**
* Remove removePhoto
*
* #param \Immo\FichierBundle\Entity\ImmeubleHasPhoto $photo
*/
public function removePhotos(\Immo\FichierBundle\Entity\ImmeubleHasPhoto $photo)
{
$this->photos->removeElement($photo);
}
/**
* {#inheritdoc}
*/
public function setPhotos($photos)
{
$this->photos = new ArrayCollection();
foreach ($photos as $photo) {
$this->addPhoto($photo);
}
}
/**
* Get photo
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPhotos()
{
return $this->photos;
}
}
The admin class :
/**
* #param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->tab('Général')
->with('Général')
->add('numero')
->add('agence')
->add('adresse','sonata_type_model_list')
->add('vente')
->add('coproindiv')
->add('exregulier')
->end()
->end()
->tab('Photos')
->with('Liste photos')
->add('photos', 'sonata_type_collection', array(
'label' => false,
'type_options' => array('delete' => true),
'cascade_validation' => true,
'btn_add' => 'Ajouter une photo',
"required" => false
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'ordre'
)
)
->end()
->end()
;
}
The join entity :
<?php
namespace Immo\FichierBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* ImmeubleHasPhoto
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Immo\FichierBundle\Entity\ImmeubleHasPhotoRepository")
*/
class ImmeubleHasPhoto
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255,nullable=true)
*/
private $nom;
/**
* #var integer
* #ORM\Column(name="ordre", type="integer")
*/
private $ordre;
/**
* #ORM\ManyToOne(targetEntity="Immeuble", inversedBy="photos",cascade={"all"},fetch="LAZY")
* #ORM\JoinColumn(name="immeuble_id", referencedColumnName="id", nullable=false)
*/
private $immeuble;
/**
* #var \Application\Sonata\MediaBundle\Entity\Media
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media",cascade={"all"},fetch="LAZY")
* #ORM\JoinColumn(name="photo_id", referencedColumnName="id", nullable=false)
*/
private $photo;
public function __construct() {
}
public function __toString() {
return $this->getNom();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function setImmeuble(\Immo\FichierBundle\Entity\Immeuble $immeuble)
{
$this->immeuble = $immeuble;
return $this;
}
/**
* Get Immeuble
*
* #return \Immo\FichierBundle\Entity\Immeuble
*/
public function getImmeuble()
{
return $this->immeuble;
}
/**
* Set photo
*
* #param string $photo
* #return Application\Sonata\MediaBundle\Entity\Media
*/
public function setPhoto(\Application\Sonata\MediaBundle\Entity\Media $photo=null)
{
$this->photo = $photo;
return $this;
}
/**
* Get photo
*
* #return Application\Sonata\MediaBundle\Entity\Media
*/
public function getPhoto()
{
return $this->photo;
}
/**
* Set nom
*
* #param string $nom
* #return ImmeubleHasPhoto
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set ordre
*
* #param integer $ordre
* #return ImmeubleHasPhoto
*/
public function setOrdre($ordre)
{
$this->ordre = $ordre;
return $this;
}
/**
* Get ordre
*
* #return integer
*/
public function getOrdre()
{
return $this->ordre;
}
}
And finally the admin class for my join entity :
/**
* #param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$link_parameters = array();
if ($this->hasParentFieldDescription()) {
$link_parameters = $this->getParentFieldDescription()->getOption('link_parameters', array());
}
if ($this->hasRequest()) {
$context = $this->getRequest()->get('context', null);
if (null !== $context) {
$link_parameters['context'] = $context;
}
}
$formMapper
->add('nom',null,array('label'=>'Titre'))
->add('photo','sonata_type_model_list', array('required' => false), array(
'link_parameters' => array('context' => 'Photos_immeuble')
))
->add('ordre','integer')
;
}
Is there something wrong? I've passe many day to find why I'm unable to attache image but I found nothing.... I really think this bundle isn't functionnal....
Thanks for your help.
I would like to know how to save the accent character é as é in a mysql database when it is inserted in a form in Symfony2. The explanation is as below:
This the code of the form builder I have:
<?php
namespace Ikproj\GroupeBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class MessagesType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('contenu','textarea', array('attr' => array('rows' => '6','cols' => '40')));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ikproj\GroupeBundle\Entity\Messages'
));
}
/**
* #return string
*/
public function getName()
{
return 'ikproj_groupebundle_messages';
}
}
This is the code of the entity belonged to the form builder above:
<?php
namespace Ikproj\GroupeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Messages
*
* #ORM\Table(name="messages")
* #ORM\Entity(repositoryClass="Ikproj\GroupeBundle\Entity\MessagesRepository")
*/
class Messages
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="actor", type="integer")
*/
private $actor;
/**
* #var integer
*
* #ORM\Column(name="subject", type="integer")
*/
private $subject;
/**
* #var string
*
* #ORM\Column(name="contenu", type="string")
*/
private $contenu;
/**
* #var string
*
* #ORM\Column(name="status", type="string", length=10)
*/
private $status;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=10)
*/
private $type;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set actor
*
* #param integer $actor
* #return Messages
*/
public function setActor($actor)
{
$this->actor = $actor;
return $this;
}
/**
* Get actor
*
* #return integer
*/
public function getActor()
{
return $this->actor;
}
/**
* Set subject
*
* #param integer $subject
* #return Messages
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* Get subject
*
* #return integer
*/
public function getSubject()
{
return $this->subject;
}
/**
* Set contenu
*
* #param string $contenu
* #return Messages
*/
public function setContenu($contenu)
{
$this->contenu = $contenu;
return $this;
}
/**
* Get contenu
*
* #return string
*/
public function getContenu()
{
return $this->contenu;
}
/**
* Set status
*
* #param string $status
* #return Messages
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set type
*
* #param string $type
* #return Messages
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
}
This is the code of the controller I have:
public function SendMessageAction(Request $request, $actor, $subject, $cible) {
$message = new Messages();
$form = $this->createForm(new MessagesType(), $message);
$em = $this->getDoctrine()->getManager();
$actor1 = $actor;
$subject1 = $subject;
$status1 = "unseen";
$cible1 = $cible;
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isValid()) {
$message->setActor($actor1);
$message->setSubject($subject1);
$message->setStatus($status1);
$message->setType($cible1);
$em->persist($message);
$em->flush();
return $this->redirect($this->generateUrl('task_success'));
}
}
else {
return $this->render('IkprojGroupeBundle:Messages:SendMessage.html.twig', array(
'form' => $form->createView(),
'actor' => $actor,
'subject' => $subject,
'cible' => $cible
));
}
}
And this is the code of the file config.yml belonged to the doctrine configuration:
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
The problem is that when I insert the accent character é in the form then I valid, it will be saved in the database as é not é as you can see in screenshot below:
Whereas when I run the code below in Symfony2:
<?php
$tab = $_REQUEST['table'];
$a = $tab[0];
$b = $tab[1];
$con=mysqli_connect("localhost","root","","wkayetdb");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"INSERT INTO messages(actor,subject,contenu,status,type) VALUES ($a,$b,'é','unseen','G')");
mysqli_close($con);
?>
it works correctly and the character é will be saved as é as you can see below:
So, my questions are:
What is wrong in my code?
How can I save é as é in a mysql database once it is inserted in a form in Symfony2 ?
I do not know why you want to do that
but if you want to do this, simply comment that line "charset: UTF8"
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
# charset: UTF8
Using VS 2012 and .NET 4.0, I have the following code which correctly deserializes an XML file:
XML File:
<?xml version="1.0"?>
<Codes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<Code>
<AccpacCode>CA9998</AccpacCode>
<LAC>90699999999999999</LAC>
<SCSCode>SDI</SCSCode>
</Code>
<Code>
<AccpacCode>ORWC</AccpacCode>
<LAC>94199999999999999</LAC>
<SCSCode>WC</SCSCode>
</Code>
<Code>
<AccpacCode>AK9999</AccpacCode>
<LAC>90299999999999999</LAC>
<SCSCode>UI</SCSCode>
<ParentEmployerAccpacCode>AKSUTA</ParentEmployerAccpacCode>
</Code>
<Codes>
XSD File:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Codes" xmlns="SerializeObservableCollection" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="Codes" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Code">
<xs:complexType>
<xs:sequence>
<xs:element name="AccpacCode" type="xs:string" minOccurs="0" />
<xs:element name="LAC" type="xs:string" minOccurs="0" />
<xs:element name="SCSCode" type="xs:string" minOccurs="0" />
<xs:element name="ParentEmployerAccpacCode" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
C# Code:
try
{
XmlSerializer _serializer = new XmlSerializer(typeof(Codes));
// A file stream is used to read the XML file into the ObservableCollection
using (StreamReader _reader = new StreamReader(#"LocalCodes.xml"))
{
var codes = _serializer.Deserialize(_reader) as Codes;
}
}
catch (Exception ex)
{
// Catch exceptions here
}
I would like to put the results of the deserialization into an ObservableCollection and have found examples that say the following should work:
ObservableCollection<Codes> CodeCollection;
...
try
{
XmlSerializer _serializer = new XmlSerializer(typeof(ObservableCollection<Codes>));
// A file stream is used to read the XML file into the ObservableCollection
using (StreamReader _reader = new StreamReader(#"LocalCodes.xml"))
{
CodeCollection = _serializer.Deserialize(_reader) as ObservableCollection<Codes>;
}
}
When I run this code I get an error message of "There is an error in XML document (2, 2)." and an inner exception of "<Codes xmlns=''> was not expected." I have seen mention of needing a default constructor to make this work and the Codes.cs class does have one (it is the file generated by VS 2012 by the XSD file). here is a snippet of the Codes.cs file:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#pragma warning disable 1591
namespace SerializeObservableCollection {
/// <summary>
///Represents a strongly typed in-memory cache of data.
///</summary>
[global::System.Serializable()]
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")]
[global::System.Xml.Serialization.XmlRootAttribute("Codes")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")]
public partial class Codes : global::System.Data.DataSet {
private CodeDataTable tableCode;
private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public Codes() {
this.BeginInit();
this.InitClass();
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
base.Relations.CollectionChanged += schemaChangedHandler;
this.EndInit();
}
What do I need to change/fix to get this to work and populate the ObservableCollection?
#BrianKE I doubt very much this will still be of use to you, but maybe it will be of use to someone else. I had the same problem as you today. Took me half the day to figure it out.
First, the message you are seeing is because the type you are specifying...
XmlSerializer _serializer = new XmlSerializer(typeof(ObservableCollection<Codes>));
..is not an ObservableCollection. If the type is wrong you get this error. Codes needs to be an observable collection for your statement to work.
What you need is root element, currently Codes is your root element, so you need a Class just for the root and then you have a number of Code elements under this. e.g.
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class MIGRATION : object, INotifyPropertyChanged, INotifyPropertyChanging
{
private string projectNameField;
private ObservableCollection<FileDescriptions> fileDescriptionsField;
//private FileDescriptions[] fileDescriptionsField;
/// <remarks/>
//[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlElement("ProjectName")]
public string ProjectName
{
get
{
return this.projectNameField;
}
set
{
this.RaisePropertyChanging("ProjectName");
this.projectNameField = value;
this.RaisePropertyChanged("ProjectName");
}
}
/// <remarks/>
[XmlElement("FileDescriptions")]
public ObservableCollection<FileDescriptions> FileDescriptions
{
get
{
return this.fileDescriptionsField;
}
set
{
this.fileDescriptionsField = value;
this.RaisePropertyChanged("FileDescriptions");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null))
{
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
protected void RaisePropertyChanging(string propertyName)
{
System.ComponentModel.PropertyChangingEventHandler propertyChanging = this.PropertyChanging;
if ((propertyChanging != null))
{
propertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName));
}
}
}
So the Observable collection(s) is on the elements inside the deserialized Class. I know what you are talking about though, I have seen examples like you are describing, but I don't know what that is about. As far as I can tell the deserialize had nothing to do with observable collection. Unless maybe they have more than one root element? Or perhaps it is when you are not deserializing a whole XML, but just a part of one, would make sense.
Deserialize should be used only with content that was previously serialized using Serialize. Otherwise, you are just playing with fire.
You can easily open and iterate through an XML document using XDocument.
XDocument xml = XDocument.Load(filename);
var collection = new ObservableCollection<Code>();
foreach (XElement e in xml.Elements("code"))
{
collection.Add(new Code() { AccpacCode = e.Element("AccpacCode").Value,
LAC = e.Element("LAC").Value });
}
You can easily iterate in all xml.Elements and intiatiate a code object which you add to an ObservableCollection. The interface may flickr a bit though during the loading.
I'm quite new with apache cxf, I have developed a web service using this tech.
XmlSchema-1.4.2.jar, commons-logging-1.1.1.jar, cxf-2.1.3.jar, geronimo-activation_1.1_spec-1.0.2.jar, geronimo-annotation_1.0_spec-1.1.1.jar, geronimo-javamail_1.4_spec-1.3.jar, geronimo-servlet_2.5_spec-1.2.jar, geronimo-ws-metadata_2.0_spec-1.1.2.jar, jaxb-api-2.1.jar, jaxb-impl-2.1.7.jar, neethi-2.0.4.jar, saaj-api-1.3.jar, saaj-impl-1.3.2.jar, wsdl4j-1.6.2.jar, xml-resolver-1.2.jar
This is the interface:
#WebService
public interface StoreAdmin
{
boolean logIn(#WebParam(name="legajo") String legajo
,#WebParam(name="lat") String lat
,#WebParam(name="lon") String lon) throws StoreException;
boolean logOut(#WebParam(name="legajo") String legajo) throws StoreException;
boolean addItemToSystem(#WebParam(name="isbn") String isbn
,#WebParam(name="descripcion") String descripcion
,#WebParam(name="precio") double precio
,#WebParam(name="numeroTotal") int numeroTotal) throws StoreException;
#WebResult(name="item")
com.dosideas.cxf.Item getItem(#WebParam(name="isbn") String isbn) throws StoreException;
}
This is the implementation file:
package com.dosideas.cxf;
import com.dosideas.cxf.exception.StoreException;
import com.dosideas.cxf.service.ServicioEncriptacion;
import com.dosideas.cxf.service.ServicioItems;
import com.dosideas.cxf.service.ServicioUsuarios;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jws.WebService;
/**
*
* #author alonso
*/
#WebService(endpointInterface = "com.dosideas.cxf.StoreAdmin",serviceName="storeAdmin")
public class StoreAdminImpl implements StoreAdmin{
//injectd by spring
private ServicioUsuarios servicioUsuarios;
private ServicioEncriptacion servicioEncriptacion;
private ServicioItems servicioItems;
//constructor...
StoreAdminImpl(ServicioUsuarios _servicioUsuarios
, ServicioEncriptacion _servicioEncriptacion
,ServicioItems _servicioItems)
{
this.servicioUsuarios=_servicioUsuarios;
this.servicioEncriptacion=_servicioEncriptacion;
this.servicioItems=_servicioItems;
}
...
// there are more methods but I don't put here, not relevant
public Item getItem(String isbn) throws StoreException {
return servicioItems.getItem(isbn);
}
public ServicioUsuarios getServicioUsuarios()
{
return servicioUsuarios;
}
}
ServicioItemsImpl.getItem method:
hashMapItems is a concurrentHashMap
public Item getItem(String isbn) throws StoreException
{
Logger.getLogger(ServicioItemsImpl.class.getName()).log(Level.INFO, "ServicioItemsImpl. INIT getItem.");
Item item = (Item ) ServicioItemsImpl.hashMapItems.get(isbn);
if (item==null)
{
Logger.getLogger(ServicioItemsImpl.class.getName()).log(
Level.WARNING, "ServicioItemsImpl. METHOD: getItem. ERROR. el item con isbn: {0} no existe en el sistema.", isbn);
//throw new StoreException("27",isbn,null);
}
else
Logger.getLogger(ServicioItemsImpl.class.getName()).log(
Level.INFO, "ServicioItemsImpl. END isbn´s Item: {0}",item.getIsbn());
return item;
}
the applicationContext.xml:
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<!-- Declaramos el bean implementación del Servicio Web. Como vemos, es
un bean más de Spring, por lo que podemos inyectarle dependencias,
interceptores, y demás.
-->
<bean id="holaMundoImpl" class="com.dosideas.cxf.HolaMundoImpl"/>
<bean id="servicioUtiles" class="com.dosideas.cxf.service.ServicioUtilesImpl"/>
<bean id="servicioUsuarios" class="com.dosideas.cxf.service.ServicioUsuariosImpl">
<constructor-arg ref="servicioUtiles"/>
<constructor-arg ref="servicioEncriptacion"/>
</bean>
<bean id="servicioEncriptacion" class="com.dosideas.cxf.service.ServicioEncriptacionImpl"/>
<bean id="servicioItems" class="com.dosideas.cxf.service.ServicioItemsImpl"/>
<bean id="servicioApuntesContables" class="com.dosideas.cxf.service.ServicioApuntesContablesImpl"/>
<bean id="storeImpl" class="com.dosideas.cxf.StoreImpl">
<constructor-arg ref="servicioUsuarios"/>
<constructor-arg ref="servicioEncriptacion"/>
<constructor-arg ref="servicioItems"/>
<constructor-arg ref="servicioApuntesContables"/>
</bean>
<bean id="storeAdminImpl" class="com.dosideas.cxf.StoreAdminImpl">
<constructor-arg ref="servicioUsuarios"/>
<constructor-arg ref="servicioEncriptacion"/>
<constructor-arg ref="servicioItems"/>
</bean>
<!-- Declaramos el endpoint de nuestro servicio web, indicando cual es la
clase de implementación. En el atributo "implementor" podemos escribir
el nombre completo de la clase implementación, o referenciar a un
bean de Spring usando un # seguido del nombre del bean.
-->
<jaxws:endpoint
id="holaMundo"
implementor="#holaMundoImpl"
address="/HolaMundo" />
<jaxws:endpoint
id="store"
implementor="#storeImpl"
address="/StoreImpl" />
<jaxws:endpoint
id="storeAdmin"
implementor="#storeAdminImpl"
address="/StoreAdminImpl" />
this is my test junit file:
#Test
public void testGetItem()
{
Logger.getLogger(StoreAdminTest.class.getName()).log(Level.INFO, "INIT testGetDescriptionItem");
try
{
boolean retorno = instance.addItemToSystem("8717418323691", "Castle Tercera Temporarada DVD",39.95,100);
assertEquals(true,retorno);
//broken here
//org.apache.cxf.interceptor.Fault: Marshalling Error: com.dosideas.cxf.Item is not known to this context
Item item = instance.getItem("8717418323691");
assertEquals(true, item!=null);
assertEquals("Castle Tercera Temporarada DVD",item.getDescripcion());
} catch (StoreException ex) {
Logger.getLogger(StoreAdminTest.class.getName()).log(Level.SEVERE, null, ex);
}
Logger.getLogger(StoreAdminTest.class.getName()).log(Level.INFO, "END testGetDescriptionItem");
}
the item pojo class:
package com.dosideas.cxf;
/**
*
* #author alonso
*/
public class Item {
private String isbn;
private String descripcion;
private double precio;
private int numeroTotal;
Item(){};
Item(String isbn,String descripcion,double precio,int numeroTotal)
{
this.isbn=isbn;
this.descripcion=descripcion;
this.precio=precio;
this.numeroTotal=numeroTotal;
};
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public int getNumeroTotal() {
return numeroTotal;
}
public void setNumeroTotal(int numeroTotal) {
this.numeroTotal = numeroTotal;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public void decrementarNumeroTotal()
{
if (getNumeroTotal()>0)
setNumeroTotal(getNumeroTotal() - 1);
else
setNumeroTotal(0);
}
}
The exception log:
org.apache.cxf.interceptor.Fault: Marshalling Error: com.dosideas.cxf.Item is not known to this context
I don't know what´s going on, and I spent 3 days reading blogs, please help!!
i have solved my problem, sorry, the default scope constructor wasnt public, arggg. anyway, thx the answer