Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "replace" filter expects an array or "Traversable" as replace values, got "string"

Tags:

php

twig

symfony

I'm using php 5.6 to develop an app but I want to upgrade my php to 7.0. The fact is, when I build a form the app give me this error: The "replace" filter expects an array or "Traversable" as replace values, got "string".

Error

This is the code I'm using to build the form:

<?php

namespace POZO\MetrajeBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MetrajeDiarioType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('metrosPerforados', null, array('label'=>'commons.drillMt'))
            ->add('sidetrack', null, array('label'=>'commons.sidetrack'))
            ->add('descripcion', null, array(
                'label' => 'commons.description',
                'label_attr' => array("class" => "hide"),
                "attr" => array("class" => "hide")
            ))
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'POZO\MetrajeBundle\Entity\MetrajeDiario',
            'translation_domain' => 'labels'
        ));
    }

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

I get the error when the line {{ form_rest(form) }} is executed.

This is the entity.

<?php

namespace POZO\MetrajeBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContext;

/**
 * MetrajeDiario
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="POZO\MetrajeBundle\Entity\MetrajeDiarioRepository")
 * @Assert\Callback(methods={"validarMetraje"})
 */
class MetrajeDiario
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fecha", type="date")
     */
    private $fecha;

    /**
     * @var float
     *
     * @ORM\Column(name="metrosPerforados", type="float")
     */
    private $metrosPerforados;

    /**
     * @var float
     *
     * @ORM\Column(name="profundidadInicial", type="float")
     */
    private $profundidadInicial;

    /**
     * @ORM\ManyToOne(targetEntity="DIPP\PozoBundle\Entity\Pozo")
     * @ORM\JoinColumn(name="pozo_id", referencedColumnName="id", nullable=false)
     */
    private $pozo;

    /**
     * @var string
     *
     * @ORM\Column(name="descripcion", type="text", nullable=true)
     */
    private $descripcion;

    /**
     * @var boolean
     *
     * @ORM\Column(name="sidetrack", type="boolean", nullable=true)
     */
    private $sidetrack;

    /**
     * @param ExecutionContext $context
     * @return void
     */
    public function validarMetraje(ExecutionContext $context)
    {
        if($this->sidetrack)
        {
            if ( $this->metrosPerforados >= $this->profundidadInicial )
            {
                $context->addViolationAt('metrosPerforados','Un sidetrack debe ser menor que la profundidad inicial.');
            }
        }
        else
        {
            if ( $this->metrosPerforados < $this->profundidadInicial )
            {
                $context->addViolationAt('metrosPerforados','El metraje debe ser mayor o igual que la profundidad inicial.');
            }
        }
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get fecha
     *
     * @return \DateTime
     */
    public function getFecha()
    {
        return $this->fecha;
    }

    /**
     * Set fecha
     *
     * @param \DateTime $fecha
     * @return MetrajeDiario
     */
    public function setFecha($fecha)
    {
        $this->fecha = $fecha;

        return $this;
    }

    /**
     * Get metrosPerforados
     *
     * @return float
     */
    public function getMetrosPerforados()
    {
        return $this->metrosPerforados;
    }

    /**
     * Set metrosPerforados
     *
     * @param float $metrosPerforados
     * @return MetrajeDiario
     */
    public function setMetrosPerforados($metrosPerforados)
    {
        $this->metrosPerforados = $metrosPerforados;

        return $this;
    }

    /**
     * Get profundidadInicial
     *
     * @return float
     */
    public function getProfundidadInicial()
    {
        return $this->profundidadInicial;
    }

    /**
     * Set profundidadInicial
     *
     * @param float $profundidadInicial
     * @return MetrajeDiario
     */
    public function setProfundidadInicial($profundidadInicial)
    {
        $this->profundidadInicial = $profundidadInicial;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     * @return MetrajeDiario
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get sidetrack
     *
     * @return boolean
     */
    public function getSidetrack()
    {
        return $this->sidetrack;
    }

    /**
     * Set sidetrack
     *
     * @param boolean $sidetrack
     * @return MetrajeDiario
     */
    public function setSidetrack($sidetrack)
    {
        $this->sidetrack = $sidetrack;

        return $this;
    }

    /**
     * Get pozo
     *
     * @return \DIPP\PozoBundle\Entity\Pozo
     */
    public function getPozo()
    {
        return $this->pozo;
    }

    /**
     * Set pozo
     *
     * @param \DIPP\PozoBundle\Entity\Pozo $pozo
     * @return MetrajeDiario
     */
    public function setPozo(\DIPP\PozoBundle\Entity\Pozo $pozo = null)
    {
        $this->pozo = $pozo;

        return $this;
    }

}

This is controller code section that is involved to creation the form:

/**
 * Creates a new MetrajeDiario entity.
 *
 * @Route("/", name="metrajediario_create")
 * @Method("POST")
 * @Template("MetrajeBundle:MetrajeDiario:new.html.twig")
 */
public function createAction(Request $request)
{
    $entity = new MetrajeDiario();
    $form = $this->createCreateForm($entity);
    $em = $this->getDoctrine()->getManager();
    $servicepozo = $this->get('service.pozo');
    $sum = $em->getRepository('MetrajeBundle:MetrajeDiario')->sumAllMetrosPerforados($servicepozo->getPozoActual());

    if (!$sum) {
        $sum = 0;
    }
    $entity->setProfundidadInicial($sum);
    $form->handleRequest($request);

    try {
        /** validate beging */
        $output = $this->validate($entity, $sum);
        /** validate end */
        if ($form->isValid() && $output) {
            $em = $this->getDoctrine()->getManager();

            $servicepozo = $this->get('service.pozo');
            $entity
                ->setPozo($servicepozo->getPozoActual())
                ->setFecha($servicepozo->getFechaActual())
                ->setMetrosPerforados(
                    $entity->getMetrosPerforados() - $sum
                );

            $em->persist($entity);
            $em->flush();
            $this->get('service.message')->addSuccess($this->get('translator')->trans('status.create'));

            return $this->redirect($this->generateUrl('metrajediario_show', array('id' => $entity->getId())));
        }
    } catch (\Exception $e) {
        $this->get('service.message')->addError($this->get('translator')->trans('metraje.error.create'));
    }

    return array(
        'entity' => $entity,
        'form' => $form->createView(),
        'sum' => $sum,
    );
}

/**
 * Creates a form to create a MetrajeDiario entity.
 *
 * @param MetrajeDiario $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(MetrajeDiario $entity)
{
    $form = $this->createForm(new MetrajeDiarioType(), $entity, array(
        'action' => $this->generateUrl('metrajediario_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => $this->get('translator')->trans('globals.add', array(), 'buttons'), 'attr' => array('class' => 'btn')));

    return $form;
}

/**
 * Displays a form to create a new MetrajeDiario entity.
 *
 * @Route("/new", name="metrajediario_new")
 * @Method("GET")
 * @Template()
 */
public function newAction()
{
    $entity = new MetrajeDiario();


    $em = $this->getDoctrine()->getManager();
    $servicepozo = $this->get('service.pozo');
    $sum = $em->getRepository('MetrajeBundle:MetrajeDiario')->sumAllMetrosPerforados($servicepozo->getPozoActual());
    $sugr = $em->getRepository('ReportesDiariosBundle:ParteOperacional')->findOneBy(array('pozo' => $servicepozo->getPozoActual(), 'fecha' => $servicepozo->getFechaActual(), 'hora' => 4));

    if (!$sum) {
        $sum = 0;
    }


    $entity->setMetrosPerforados($sugr == null ? 0 : $sugr->getProfundidadActual() );
    $form = $this->createCreateForm($entity);
    return array(
        'entity' => $entity,
        'form' => $form->createView(),
        'sum' => $sum
    );
}

And finally this is the view:

{% extends 'PlantillasBundle:Plantillas:forms.html.twig' %}

{% form_theme form 'PlantillasBundle:Plantillas/labels:bootstrap_four_col.html.twig' %}
{% form_theme form.sidetrack 'PlantillasBundle:Plantillas/nolabels:bootstrap_nolabels_four_col.html.twig' %}
{% form_theme form.descripcion 'PlantillasBundle:Plantillas/labels:bootstrap_one_col.html.twig' %}

{% block formtitle -%}
    <h3> {{ 'metraje.new' | trans({}, 'titles') }}</h3>
{% endblock %}

{% block formbuttons %}
    <div class="btn-group pull-right">
        <a class="btn btn-info" href="{{ path('metrajediarios') }}">
            <i class="fa fa-list-ul"></i> {{ 'actions.index' | trans({}, 'buttons') }}
        </a>
    </div>
{% endblock %}

{% block formbody -%}
    {{ form_start(form) }}
    <div class="span3">
        <label><b> {{ 'metraje.lastdepth' | trans({}, 'labels') }}</b></label>
        <input id='ultimo-metraje' type="text" readonly value="{{ sum }}"/>
    </div>
    {{ form_rest(form) }}
    {{ form_end(form) }}
{% endblock %}

{% block scripts %}
    {{ parent() }}
    <script type='text/javascript' src='{{ asset('bundles/utiles/js/onclick.js') }}'></script>
    <script>
        $(document).ready(function () {
            onClickHide("pozo_metrajebundle_metrajediario_descripcion", "pozo_metrajebundle_metrajediario_sidetrack");
            $('#pozo_metrajebundle_metrajediario_sidetrack').on('click', function () {
                onClickHide("pozo_metrajebundle_metrajediario_descripcion", "pozo_metrajebundle_metrajediario_sidetrack");
            });

            var $btn = $('button[data-info=crear]');
            $btn.on('click', function (e) {
                $('div.has-error').removeClass('has-error');
                var campo = $('#pozo_metrajebundle_metrajediario_metrosPerforados');
                var nuevo = parseFloat($('#pozo_metrajebundle_metrajediario_metrosPerforados').val());
                var ultimo = parseFloat($('#ultimo-metraje').val());
                var isSidetrack = $('#pozo_metrajebundle_metrajediario_sidetrack:checked').length == 0;
                if (isSidetrack && (nuevo < ultimo)) {
                    $($(campo).parents('div').get(0)).addClass('has-error');
                    mostrarModalAlert('{{ 'message.error' | trans({}, 'titles') }}', '{{ 'metraje.error.modalalert2' | trans({}) }}');
                    return false;
                }
                else if (!isSidetrack && !(nuevo < ultimo)) {
                    $($(campo).parents('div').get(0)).addClass('has-error');
                    mostrarModalAlert('{{ 'message.error' | trans({}, 'titles') }}', '{{ 'metraje.error.modalalert1' | trans({}) }}');
                    return false;
                }
                $guardar.trigger('guardar');
                return false;
            });
        });
    </script>
{% endblock %}

And there are the tree form_theme we apply to form's widgets.

{% block form_row -%}
    <div class="clearfix"></div>
    <div class="row-fluid {% if (not compound or force_error|default(false)) and not valid %} has-error{% endif %}">
        {{- form_label(form) -}}
        {{- form_widget(form) -}}

    </div>
{%- endblock form_row %}


{% block form_row -%}
    <div class="span3 {% if (not compound or force_error|default(false)) and not valid %} has-error{% endif %}">
        {#{{- form_label(form) -}}#}
        {{- form_widget(form) -}}

    </div>
{%- endblock form_row %}



{% block form_row -%}
    <div class="span3 {% if (not compound or force_error|default(false)) and not valid %} has-error{% endif %}">
        {#{{- form_label(form) -}}#}
        {{- form_widget(form) -}}

    </div>
{%- endblock form_row %}
like image 695
Andris Villalón de la Cruz Avatar asked Sep 13 '17 18:09

Andris Villalón de la Cruz


1 Answers

I had a similar issue - caused I think by an updated version of twig but not 100% sure. I suspect, that somewhere in your twig template (perhaps another not in your examples that is being extended?) you have a replace function like this:

{{something|replace('x','y')}}

which you'll need to change to this syntax:

{{something|replace({'x':'y'})}}

like image 177
andyxmas Avatar answered Oct 06 '22 01:10

andyxmas