简体   繁体   中英

Array to string conversion error when trying to use each validator Yii2

I been trying to develop a dynamic form that generates based on question in a database, but I been having a lot of problems with the validation of the form. I searched everywhere, but not non of the available ones seem to work. The most promising solution was using the "each" validator, but when I try using it, it gave me and "Array to string conversion" error that I wasn't able to fix. If anyone knew what could be the problem with my code I would appreciate it. Here is the code, it's a little messy because I was testing a lot of things. Model

   public $file;
public $respuestaCorta = [];

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['idpregunta', 'idinscripcion', 'respuesta', "respuestaCorta"], 'required'],
            [['idpregunta', 'idinscripcion'], 'integer'],
            [['respuesta'], 'each', 'rule' => ['string', 'max' => 500, "message" => "Esta campo no debe tener mas de 500 caracteres"]],
            [['respuestaCorta'], 'each', 'rule' => ['string', 'max' => 50, "message" => "Esta campo no debe tener mas de 50 caracteres"]],
            [['file'], "file", "extensions" => ["zip", "rar", "pdf"], 'skipOnEmpty' => false, 'maxSize' => 5000000, 'tooBig' => 'El limite de archivo son de 5 mb'],
            [['idpregunta'], 'exist', 'skipOnError' => true, 'targetClass' => Pregunta::className(), 'targetAttribute' => ['idpregunta' => 'id']],
            [['idinscripcion'], 'exist', 'skipOnError' => true, 'targetClass' => Inscripcion::className(), 'targetAttribute' => ['idinscripcion' => 'idInscripcion']],
        ];
    }

    public function upload()
    {
        if ($this->validate()) {
            $this->file->saveAs("../web/eventos/formularios/archivos/" . $this->file->baseName . '.' . $this->file->extension);
            return true;
        } else {
            return false;
        }
    }

view

<div class="responder-formulario container">
<div class="pb-5">
    <div class="card-header darkish_bg text-white">
        <h3>Formulario de Pre-Inscripción</h3>
        <h5>Responda con <span class="pinkish_text">cuidado</span>, no se pueden editar las respuestas.</h5>
    </div>
</div>
<?php
$form = ActiveForm::begin([
    'id' => 'respuestas-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
<?php foreach ($preguntas as $i => $pregunta) : ?>
    <div class='card mb-5'>
       <div class='card-header darkish_bg text-white'>
       <h5>Pregunta <?= ($i + 1) ?></h5>
    </div>
    <div class='card-body'>
       <?= $pregunta->descripcion ?>
    </div>
    <div class='card-footer'>
        <?php if($pregunta->tipo == 1): ?>
            <?= $form->field($model, 'respuestaCorta')->textInput(['maxlength' => true])->label(false) ?>
        <?php endif; ?>
        <?php if($pregunta->tipo == 2): ?>
            <?= $form->field($model, 'respuesta')->textarea(['maxlength' => true])->label(false) ?>
        <?php endif; ?>
        <?php if($pregunta->tipo == 3): ?>
            <?= $form->field($model, 'file')->fileInput()->label(false) ?>
        <?php endif; ?>
    <?php if ($respuestaYaHechas[$i] == false) : ?>
       <?php $url = Url::toRoute(["respuesta/create?id=" . $pregunta->id . "&id2=" . $idInscripcion]) ?>
        <?= Html::a('Completar ' . ($i + 1), $url, [
            'class' => 'btn btn-lg responderPregunta'
        ]); ?>
    <?php else : ?>

    <?php if($pregunta->tipo == 3): ?>
        <span>Respuesta: <?= Html::encode($respuestaYaHechas[$i]->respuesta) ?></span>
    <?php else: ?>
            <span>Respuesta: <?= Html::a("Descargar", Html::encode($respuestaYaHechas[$i]->respuesta), ['class' => 'btn btn-lg btn-outline-success']) ?></span>
    <?php endif; ?>
    <?php endif; ?>
    </div>
    </div>
<?php endforeach; ?>
<?php ActiveForm::end() ?>

<br><br>

<?= Html::a('Volver Atrás', Url::toRoute("eventos/ver-evento/" . $evento->nombreCortoEvento), ['class' => 'btn btn-lg btn-outline-success']); ?>

Controller

    public function actionResponderFormulario($slug) {
    
        $evento = $this->findModel("", $slug);
        $inscripcion = Inscripcion::find()->where(["idEvento" => $evento->idEvento, "idUsuario" => Yii::$app->user->identity->idUsuario])
            ->andWhere(["<>", "estado", 1])
            ->andWhere(["<>", "estado", 2])
            ->one();
    
        if ($inscripcion != null) {
            $preguntas = Pregunta::find()->where(["idEvento" => $evento->idEvento])->all();
    
            $respuestaYaHechas = [];
            foreach ($preguntas as $pregunta){
                $respuesta = RespuestaSearch::find()->where(["idpregunta" => $pregunta->id, "idinscripcion" => $inscripcion->idInscripcion])->one();
                if($respuesta == null){
                    array_push($respuestaYaHechas, false);
                }else{
                    array_push($respuestaYaHechas, $respuesta);
                }
            }
            $model = new RespuestaTest();
            return $this->render('responderFormulario',
                            ["preguntas" => $preguntas,
                                "evento" => $evento,
                                "idInscripcion" => $inscripcion->idInscripcion,
                                "respuestaYaHechas" => $respuestaYaHechas,
                                "model" => $model]);
        } else {
            return $this->goHome();
        }
    }

Thank you

I solved it, it was a really easy thing.

I needed to declare the name in the input as an array:

<?= $form->field($model, 'respuestaCorta[$i]')->textInput(['maxlength' => true])->label(false) ?>

put in rule name= yourattribute ==>

[['name'], 'eachAlphaNumeric'],

and custom function for validation for each attribute

 public function eachAlphaNumeric($attribute)
    {
        $alphaNumeric = true;
        $arr = explode(',', $this->$attribute);
        foreach ($arr as $key) {

            if (preg_match("/^[a-zA-Z0-9]*$/", $key) != 1 || in_array($key, ['NA', 'NULL', 'nill'])) {
                $alphaNumeric = false;
                $this->addError($attribute, 'invalid_value');
                break;
            }
        }

        return $alphaNumeric;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM