Monday , September 25 2023
Home / Zend Framework / Validate records in zf2

Validate records in zf2

Inside the controller :

Select Code
public function addAction() {
        $form = new TestForm();
        $form->get('submit')->setAttribute('value', 'Add');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $test = new Test();
            if ($form->isValid()) {
                if($this->getTestTable()->validateRecord($test, 'field1', 'test')){
                    $this->flashMessenger()->addMessage('Record added in db');
                    // Redirect to list of tests
                    return $this->redirect()->toRoute('test');
                    $this->flashMessenger()->addMessage('Record Exist in DB');
                    return $this->redirect()->toRoute('test', array('action' => 'add'));
        return array('form' => $form,'flashMessages' => $this->flashMessenger()->getMessages());

Inside the model

Select Code
public function validateRecord($data,$field,$table){
        $select = new ZendDbSqlSelect();
               ->where->equalTo($field, $data->$field);
        $validator = new ZendValidatorDbRecordExists($select);
        if ($validator->isValid($data->$field)) {
            return false;
        else {
            return true;

About v.shakya

I am V.Shakya, Software Developer & Consultant I like to share my ideas, views and knowledge to all of you who come across my website. I am young, enthusiastic, highly motivated and self disciplined person. I completed my studies in Master of Computer Application and currently giving my technical expertise to one of the Big IT company. I have more than fifteen years of experience in vast field of Programming , Designing and Development of websites and various software's.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.