繁体   English   中英

尝试使用每个验证器 Yii2 时数组到字符串的转换错误

[英]Array to string conversion error when trying to use each validator Yii2

我一直在尝试开发一个基于数据库中的问题生成的动态表单,但是我在表单验证方面遇到了很多问题。 我到处搜索,但并非没有可用的似乎有效。 最有希望的解决方案是使用“每个”验证器,但是当我尝试使用它时,它给了我和我无法修复的“数组到字符串转换”错误。 如果有人知道我的代码可能有什么问题,我将不胜感激。 这是代码,它有点乱,因为我正在测试很多东西。 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;
        }
    }

看法

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

谢谢

我解决了,这很容易。

我需要将输入中的名称声明为数组:

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

输入规则名称=你的属性==>

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

和自定义 function 用于验证每个属性

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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