We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 34075 ☆ A M B ☆
    • 130 Posts
    I would like to check if an e-mail address does not allready exists in the database before adding the new record. So, it must be unique.

    I allready have some other validation in my schema, but for this I guess I need to do some PHP validation?


    This is what I have done so far:
    <?php
    $validator = $subscriber->getValidator();
    
    		/* save */
    		if ($validator == false || $subscriber->save() == false) {
    			
    			if($_SERVER['REQUEST_METHOD'] == 'POST')
    			{				
    				$messages = $validator->getMessages();  
         				foreach ($messages as $errorMsg) {  
             				$o .= $errorMsg['message'].'<br />';
         				}
         				$this->modx->smarty->assign('errors', $o);
    				$this->modx->smarty->assign('name', $_POST['name']);
    				$this->modx->smarty->assign('email', $_POST['email']);
    				$this->modx->smarty->assign('active', $_POST['active']);
    			}
    			
    			return $this->modx->smarty->fetch($this->config['basePath'].'templates/add_subscriber.html');
    		}
    		else
    		{
    			return $this->listSubscribers(); //terug naar overzicht
    		}
    ?>
    


    How to extend the validation, so that it only accepts new e-mailadresses?
      Jeroen Kenters

      MODX Professional | MODX Ambassador | Dutch MODX forums moderator

      website | twitter
      • 34075 ☆ A M B ☆
      • 130 Posts
      I solved it this way;
      - created a ’checkUniqueEmail’ method in my class
      - use this method in my add/edit actions (params: email address, reference to validator, subscriber id)

      In my action:

      <?php
      /* save */
      if ($validator == false || $this->checkUniqueEmail($subscriber->get('email'), $validator, $subscriber->get('id')) == false || $subscriber->save() == false) 
      {
        //show form
      }
      else
      {
        //go to index view
      }
      ?>
      


      Method
      <?php
      	function checkUniqueEmail($email, validator &$validator, $subscriber = false) 
      	{		
      		//don't check own email address (edit action)
      		if($subscriber)
      		{
      			$conditions = array(
      				'email' => $email,
      				'id:!=' => $subscriber
      			);
      		}
      		//check all records
      		else
      		{
      			$conditions = array( 'email' => $email );
      		}		
      		
      		
      		$c = $this->modx->newQuery('nwSubscriber');
      		$c->where( $conditions );
      		
      		if( $this->modx->getObject('nwSubscriber', $c ) )
      		{
      			$validator->addMessage('email', 'validEmail', 'Email address allready exists');
      			return false;
      		}
      		else
      			return true;
      	}
      ?>
      
        Jeroen Kenters

        MODX Professional | MODX Ambassador | Dutch MODX forums moderator

        website | twitter