Foros del Web » Programando para Internet » PHP » Symfony »

[SOLUCIONADO] Convertir objeto Datetime a string en symfony2

Estas en el tema de Convertir objeto Datetime a string en symfony2 en el foro de Symfony en Foros del Web. Estoy creando un formulario de ingreso de datos y tengo el siguiente error "Catchable Fatal Error: Object of class DateTime could not be converted to ...
  #1 (permalink)  
Antiguo 12/12/2013, 15:07
 
Fecha de Ingreso: septiembre-2013
Mensajes: 61
Antigüedad: 10 años, 7 meses
Puntos: 0
Convertir objeto Datetime a string en symfony2

Estoy creando un formulario de ingreso de datos y tengo el siguiente error "Catchable Fatal Error: Object of class DateTime could not be converted to string in /var/www/abcis/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php line 103 ".
En el codigo del controller he setteado la fecha de creación a la fecha actual:
Código PHP:
 /**
     * Creates a new SchoolRecord entity.
     *
     * @Route("/create", name="admission_school_record_applicant_create")
     * @Method("POST")
     * @Template("ABCAdmissionBundle:Applicant:Applicant.html.twig")
     */
    
public function createAction(Request $request)
    {   
        
$session $this->getRequest()->getSession();
        
$appId=$session->get('applicant');
            
        
$entity = new SchoolRecord();
        
$form $this->createCreateForm($entity);
        
$form->handleRequest($request);
        
$em $this->getDoctrine()->getManager("admission");
        
$applicantObject $em->getRepository('ABCAdmissionBundle:Applicant')->find($appId);
        
$entity->setApplicant($applicantObject);
        
$app=$entity->getApplicant();
        
$entity->setCreatedDate(new DateTime());
    
//    $entity->setIsCurrent('true');
               
        
if ($form->isValid()) {                 
            
$em->persist($entity);
            
$em->flush();  
            
$session $this->getRequest()->getSession();
            
$session->set('step',3);
            
$session->set('applicant',$app->getId());
            return 
$this->redirect($this->generateUrl('admission_applicants'));
        }
            
$session->set('step',2);
            
$session->set('applicant',$app->getId());
            return 
$this->redirect($this->generateUrl('admission_applicants'));
       
/* return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );*/
    

En el codigo del formulario he comentado la linea del createdDate porque lo setteo en el controller
Código PHP:
public function buildForm(FormBuilderInterface $builder, array $options)
    {      
        
$builder
            
->add('schoolName','text',array('label'=>'School name - Nombre del colegio *'))
            ->
add('fromDate','date',array('format' => 'dd-MMM-yyyy',
                                          
'years'=>range((date("Y")-14), date("Y")),
                                          
'label'=>'Attended from - Periodo desde'))
            ->
add('toDate','date',array('format' => 'dd-MMM-yyyy',
                                          
'years'=>range((date("Y")-14), date("Y")),
                                        
'label'=>'Attended to - Periodo hasta'))
            ->
add('headName','text',array('label'=>'Name of the Head - Nombre del Director'))
            ->
add('phoneNumber','text',array('label'=>'Phone number - Teléfono'))
            ->
add('eMail','text',array('label'=>'E-mail - Correo electrónico'))
            ->
add('isCurrent','choice',array(
        
'label'=>'Information of present school - Información del colegio actual *',
        
'empty_value' => 'Choose an option',
        
'choices'=> array(
            
'true' => 'Yes / Si'
            
'false' => 'No',
            )))
           
// ->add('createdDate')
            
->add('address','entity',
                 array(
'label'=>'Select a address *',
                       
'class'=>'ABCAdmissionBundle:Addresses',
                       
'property'=>'id'
                 
))
        ;
    } 
La vista la pinto de la siguiente manera:
Código HTML:
{% extends "ABCAdmissionBundle::layoutAppForm.html.twig" %}
{% block title %} School Information Form {% endblock %}

{% block contenido %}
{{form_start(form)}}
    {{form_errors(form)}}
    <div class="row-fluid">
        <div class="span12">
            {{form_row(form.schoolName, {'attr': {'class': 'span11'}}) }}
            {{ form_row(form.headName, {'attr': {'class': 'span11'}}) }}
        </div>
    </div>
     <div class="row-fluid">
        <div class="span6">
        {{form_label(form.fromDate)}}    
        {{form_widget(form.fromDate.day,{'attr': {'class': 'span3'}}) }}
        {{form_widget(form.fromDate.month,{'attr': {'class': 'span3'}}) }}
        {{form_widget(form.fromDate.year,{'attr': {'class': 'span3'}}) }}
        {{form_row(form.phoneNumber)}}
        {{form_row(form.address)}}
        </div>
        <div class="span6">
        {{form_label(form.toDate)}}
        {{form_widget(form.toDate.day, {'attr': {'class': 'span3'}}) }}
        {{form_widget(form.toDate.month,{'attr': {'class': 'span3'}}) }}
        {{form_widget(form.toDate.year,{'attr': {'class': 'span3'}}) }}
        {{form_row(form.eMail)}}
        {{form_row(form.isCurrent)}} 
        </div>    
    </div>
{{form_widget(form.save)}}
{{form_end(form)}}
{% endblock %} 
Yo creo que mi problema es que no he convertido el Datetime a string, pero no se como hacerlo. De antemano les agradezco su ayuda.
  #2 (permalink)  
Antiguo 12/12/2013, 16:28
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Convertir objeto Datetime a string en symfony2

mmm, el manejo de DateTime deberia ser transparente con Doctrine, que tipo de dato tienes en el mapping de la entidad ?
__________________
http://es.phptherightway.com/
thats us riders :)
  #3 (permalink)  
Antiguo 12/12/2013, 16:38
 
Fecha de Ingreso: septiembre-2013
Mensajes: 61
Antigüedad: 10 años, 7 meses
Puntos: 0
Respuesta: Convertir objeto Datetime a string en symfony2

Yo creo que mi verdadero problema esta en los valores fromDate y toDate de mi formulario, ya que en la entidad los tengo definidos como string. pero no se como convertir esos objetos date a string.
Adjunto parte de mi entidad:
Código PHP:

class SchoolRecord
{
    
/**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    
private $id;

    
/**
     * @var string
     *
     * @ORM\Column(name="school_name", type="string", length=150, nullable=false)
     */
    
private $schoolName;

    
/**
     * @var string
     *
     * @ORM\Column(name="from_date", type="string", length=10, nullable=false)
     */
    
private $fromDate;

    
/**
     * @var string
     *
     * @ORM\Column(name="to_date", type="string", length=10, nullable=false)
     */
    
private $toDate;

    
/**
     * @var string
     *
     * @ORM\Column(name="head_name", type="string", length=160, nullable=false)
     */
    
private $headName;

    
/**
     * @var string
     *
     * @ORM\Column(name="phone_number", type="string", length=15, nullable=true)
     */
    
private $phoneNumber;

    
/**
     * @var string
     *
     * @ORM\Column(name="e_mail", type="string", length=80, nullable=true)
     */
    
private $eMail;

    
/**
     * @var string
     *
     * @ORM\Column(name="is_current", type="string", length=255, nullable=false)
     */
    
private $isCurrent;

    
/**
     * @var \DateTime
     *
     * @ORM\Column(name="created_date", type="datetime", nullable=false)
     */
    
private $createdDate;

    
/**
     * @var \Addresses
     *
     * @ORM\ManyToOne(targetEntity="Addresses")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="address", referencedColumnName="id")
     * })
     */
    
private $address;

    
/**
     * @var \Applicant
     *
     * @ORM\ManyToOne(targetEntity="Applicant")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="applicant_id", referencedColumnName="id")
     * })
     */
    
private $applicant;

  #4 (permalink)  
Antiguo 12/12/2013, 17:11
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Convertir objeto Datetime a string en symfony2

Es que deberian ser del tipo date o datetime dependiendo de lo que necesites y no del tipo string que tienes ahora.
__________________
http://es.phptherightway.com/
thats us riders :)
  #5 (permalink)  
Antiguo 12/12/2013, 17:29
 
Fecha de Ingreso: septiembre-2013
Mensajes: 61
Antigüedad: 10 años, 7 meses
Puntos: 0
Respuesta: Convertir objeto Datetime a string en symfony2

Si lo comprendo, pero esa es la estructura de la base que me han dado, y lo que he hecho en el controlador es lo siguiente:
Código PHP:
$fromDate=$entity->getFromDate();
 
var_dump($fromDate->format("Y-m-d"));
 
$entity->setFromDate($fromDate);
 
$toDate=$entity->getToDate();
 
$toDate->format("Y-m-d");
$entity->setToDate($toDate); 
y efectivamente puedo constatar que ahora me retorna un string con la fecha ingresada, pero simplemente me sigue dando el mismo error.
  #6 (permalink)  
Antiguo 12/12/2013, 17:42
 
Fecha de Ingreso: septiembre-2013
Mensajes: 61
Antigüedad: 10 años, 7 meses
Puntos: 0
Respuesta: Convertir objeto Datetime a string en symfony2

Lo resolvi de la siguiente manera poniendo esto en el controlador:
Código PHP:
$fromDate=$entity->getFromDate();
$entity->setFromDate($fromDate->format("Y-m-d"));
$toDate=$entity->getToDate();
$entity->setToDate($toDate->format("Y-m-d")); 

Etiquetas: datetime, objeto, string, symfony2
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:25.