0

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

1
  • which version of yii2 are you using? v2.0.35 seems to have a problem with the each validator. github.com/yiisoft/yii2/issues/18051 Commented Jul 5, 2020 at 19:26

2 Answers 2

1

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) ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Actually this didn't solve it :/, sorry for the confusion
0

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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.