Problem with Primary key YII2

Hello everyone, I’m new to yii2, I have a problem that recently occurred to me which I didn’t have before, which is that the primary key of my database (id) tells me that the value is invalid despite the fact that the field in the form is filled.
BTW, I’m working in Spanish, but I’m looking for help here because the yii2 community in Spanish compared to English is literally dead.

this is the error

This is my model:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "visitas".
 *
 * @property string $vcedula
 * @property string $vnombres
 * @property string $vapellidos
 * @property string $vnacionalidad
 * @property string|null $vcorreo
 * @property string $vpersona_visita
 * @property string $vmotivo_visita
 * @property string $vpermiso
 * @property string $vpropiedad
 * @property int $vpase
 * @property string $vfecha
 * @property string|null $vobservacion
 * @property int $id_telefono
 * @property int $id_oficina
 * @property int $id_piso
 * @property int $id_estado
 *
 * @property Estado $estado
 * @property Oficina $oficina
 * @property Piso $piso
 * @property Telefono $telefono
 * @property Registro $vcedula0
 * @property Vetados $vcedula1
 */
class Visitas extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'visitas';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['vcedula', 'vnombres', 'vapellidos', 'vnacionalidad', 'vpersona_visita', 'vmotivo_visita', 'vpermiso', 'vpropiedad', 'vpase', 'vfecha', 'id_telefono', 'id_oficina', 'id_piso', 'id_estado'], 'required'],
            [['vpase', 'id_telefono', 'id_oficina', 'id_piso', 'id_estado'], 'default', 'value' => null],
            [['vpase', 'id_telefono', 'id_oficina', 'id_piso', 'id_estado'], 'integer'],
            [['vfecha'], 'safe'],
            [['vcedula'], 'string', 'max' => 8],
            [['vnombres', 'vapellidos'], 'string', 'max' => 20],
            [['vnacionalidad'], 'string', 'max' => 1],
            [['vcorreo'], 'string', 'max' => 35],
            [['vpersona_visita'], 'string', 'max' => 40],
            [['vmotivo_visita'], 'string', 'max' => 50],
            [['vpermiso', 'vpropiedad'], 'string', 'max' => 2],
            [['vobservacion'], 'string', 'max' => 80],
            [['vcedula'], 'unique'],
            [['id_estado'], 'exist', 'skipOnError' => true, 'targetClass' => Estado::className(), 'targetAttribute' => ['id_estado' => 'id_estado']],
            [['id_oficina'], 'exist', 'skipOnError' => true, 'targetClass' => Oficina::className(), 'targetAttribute' => ['id_oficina' => 'id_oficina']],
            [['id_piso'], 'exist', 'skipOnError' => true, 'targetClass' => Piso::className(), 'targetAttribute' => ['id_piso' => 'id_piso']],
            [['vcedula'], 'exist', 'skipOnError' => true, 'targetClass' => Registro::className(), 'targetAttribute' => ['vcedula' => 'rcedula']],
            [['id_telefono'], 'exist', 'skipOnError' => true, 'targetClass' => Telefono::className(), 'targetAttribute' => ['id_telefono' => 'id_telefono']],
            [['vcedula'], 'exist', 'skipOnError' => true, 'targetClass' => Vetados::className(), 'targetAttribute' => ['vcedula' => 'lcedula']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'vcedula' => 'Cedula del Visitante',
            'vnombres' => 'Nombres',
            'vapellidos' => 'Apellidos',
            'vnacionalidad' => 'Nacionalidad',
            'vcorreo' => 'Correo Electronico',
            'vpersona_visita' => 'Persona a Visitar',
            'vmotivo_visita' => 'Motivo de la Visita',
            'vpermiso' => '¿Posee pase? ',
            'vpropiedad' => '¿Posee algun equipo?',
            'vpase' => 'Numero de Pase',
            'vfecha' => 'Fecha de Ingreso',
            'vobservacion' => 'Datos Adicionales',
            'id_telefono' => 'Id Telefono',
            'id_oficina' => 'Id Oficina',
            'id_piso' => 'Id Piso',
            'id_estado' => 'Id Estado',
        ];
    }

    /**
     * Gets query for [[Estado]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getEstado()
    {
        return $this->hasOne(Estado::className(), ['id_estado' => 'id_estado']);
    }

    /**
     * Gets query for [[Oficina]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getOficina()
    {
        return $this->hasOne(Oficina::className(), ['id_oficina' => 'id_oficina']);
    }

    /**
     * Gets query for [[Piso]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getPiso()
    {
        return $this->hasOne(Piso::className(), ['id_piso' => 'id_piso']);
    }

    /**
     * Gets query for [[Telefono]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getTelefono()
    {
        return $this->hasOne(Telefono::className(), ['id_telefono' => 'id_telefono']);
    }

    /**
     * Gets query for [[Vcedula0]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getVcedula0()
    {
        return $this->hasOne(Registro::className(), ['rcedula' => 'vcedula']);
    }

    /**
     * Gets query for [[Vcedula1]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getVcedula1()
    {
        return $this->hasOne(Vetados::className(), ['lcedula' => 'vcedula']);
    }

}

This is my controller:

<?php

namespace app\controllers;

use app\models\Visitas;
use app\models\VisitasSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * VisitasController implements the CRUD actions for Visitas model.
 */
class VisitasController extends Controller
{
    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return array_merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['POST'],
                    ],
                ],
            ]
        );
    }

    /**
     * Lists all Visitas models.
     *
     * @return string
     */
    public function actionIndex()
    {
        $searchModel = new VisitasSearch();
        $dataProvider = $searchModel->search($this->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Visitas model.
     * @param string $vcedula Vcedula
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($vcedula)
    {
        return $this->render('view', [
            'model' => $this->findModel($vcedula),
        ]);
    }

    /**
     * Creates a new Visitas model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Visitas();

        if ($this->request->isPost) {
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['view', 'vcedula' => $model->vcedula]);
            }
        } else {
            $model->loadDefaultValues();
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Visitas model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $vcedula Vcedula
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($vcedula)
    {
        $model = $this->findModel($vcedula);

        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
            return $this->redirect(['view', 'vcedula' => $model->vcedula]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Visitas model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $vcedula Vcedula
     * @return \yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($vcedula)
    {
        $this->findModel($vcedula)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Visitas model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $vcedula Vcedula
     * @return Visitas the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($vcedula)
    {
        if (($model = Visitas::findOne(['vcedula' => $vcedula])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

and this is my view:

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Visitas */
/* @var $form yii\widgets\ActiveForm  


                   Identificadores 
    <?= //$form->field($model, 'id_telefono')->textInput() ?>

    <?= //$form->field($model, 'id_oficina')->textInput() ?>

    <?= //$form->field($model, 'id_piso')->textInput() ?>

    <?= //$form->field($model, 'id_estado')->textInput() ?>

*/
?>

<div class="visitas-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'vcedula')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vnombres')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vapellidos')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vnacionalidad')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vcorreo')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vpersona_visita')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vmotivo_visita')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vpermiso')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vpropiedad')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'vpase')->textInput() ?>

    <?= $form->field($model, 'vfecha')->textInput() ?>

    <?= $form->field($model, 'vobservacion')->textInput(['maxlength' => true]) ?>



    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

I don’t know if you can see something that I don’t see.

Error comes from here. vcedula must be a valid FK to the table behind Vetados
Very likely that specific key is not there in the other table

¿What do you mean that that specific key is not in the other table?, I have the table vetados with the same primary key (different name) with the same data type and length.

this is my table relationship

I mean data not tables. It seems you are inserting data in Vistas which does not have the same corresponding key in Vetados. Data must be in Vetados first before you can insert in Vistas since PK for Vista is also FK for Vetados

I’m sorry I can’t understand it, but thanks for having responded, I hope this will be useful to someone else who passes by here.

I’ll see if I try other ways, after all Linux programming is new to me.

Saludos, el pequeño gran detalle q las id NO son autoincremet, eso te genera problemas, mas aun cuando manejas grandes volumenes de data. para validar los datos si existen se coloca en las reglas: te dejo un ejemplo por si lo necesitas

<?php // unique con ajax // en el formulario <?php $form = ActiveForm::begin(['enableAjaxValidation' => true]); ?> <?php // modelo ['clientescedula', 'unique', 'targetAttribute' => ['clientescedula'], 'message' => 'Num Cedula Ya existe'], // controller use yii\web\HttpException; use yii\db\ActiveRecord; // use yii\web\Response; use yii\widgets\ActiveForm; // Create if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } ?>

Use google translate. Might be helpful or someone else can do it

Greetings, the issuer is Latino, excuse me

Thanks for the help. Months later I realize my mistake with the auto-increment identification, I used Dbvisualizer to do the auto-increment in my database, but due to an error that I still don’t know what it was, the database serials were passed to integer without being auto-increment ,Using pgadmin to create them they didn’t have any errors besides I had a mess with the PK and FK that I was confused. Thanks again.

1 Like

In Postgres world PGAdmin4 is unbeaten beast!

1 Like