문제

교리 검증의 기본 오류 메시지를 수정해야합니다. 어떻게 할 수 있습니까?

감사해요

도움이 되었습니까?

해결책

Crazyjoe 옳습니다. :-(

그러나 충분히 열심히 검색하면 방법을 찾을 수 있습니다. ;-)


교리 1.1을 사용하면 모델 수업이 확장됩니다 Doctrine_Record.
해당 클래스는이 방법을 정의합니다.

/**
 * Get the record error stack as a human readable string.
 * Useful for outputting errors to user via web browser
 *
 * @return string $message
 */
public function getErrorStackAsString()
{
    $errorStack = $this->getErrorStack();

    if (count($errorStack)) {
        $message = sprintf("Validation failed in class %s\n\n", get_class($this));

        $message .= "  " . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " had validation error" . (count($errorStack) > 1 ?  's' : null) . ":\n\n";
        foreach ($errorStack as $field => $errors) {
            $message .= "    * " . count($errors) . " validator" . (count($errors) > 1 ?  's' : null) . " failed on $field (" . implode(", ", $errors) . ")\n";
        }
        return $message;
    } else {
        return false;
    }
}

이것은 메시지를 생성하는 방법입니다. 보시다시피, 그것은 완전 자동이며 전혀 구성 할 수 없습니다. :-(


그럼에도 불구하고 OOP 덕분에 모델 클래스에서 해당 메소드를 과부하 할 수 있습니다 ...

그러나 조금 더 깨끗하기 위해서는 다음과 같습니다.

  • 새 클래스를 만듭니다 My_Doctrine_Record, 그것은 확장됩니다 Doctrine_Record
  • 해당 클래스는 오류 메시지를 사용자 정의 할 수 있도록 해당 방법을 재정의 할 것입니다.
  • 그리고 우리의 모델 클래스는 그것을 확장 할 것입니다 My_Doctrine_Record 수업.

이것은 각 모델 클래스 내에서 해당 방법의 복제를 피할 수 있습니다. 그리고 다른 날에 유용 할 수 있습니다 ...


우리의 My_Doctrine_Record::getErrorStackAsString 물론 메소드는 모델 클래스의 메소드에 의존하여 각 모델 클래스에 대한 특별 사용자 정의로 메시지를 생성하는 데 도움이 될 수 있습니다.

다음은 작동하는 예입니다. 완벽하지는 않지만 당신이 얻고 싶은 것을 안내 할 수 있습니다. ;-)


우선, 초기화 :

require_once '/usr/share/php/Doctrine/lib/Doctrine.php';
spl_autoload_register(array('Doctrine', 'autoload'));

$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_VALIDATE, Doctrine::VALIDATE_ALL);

$conn = Doctrine_Manager::connection('mysql://test:123456@localhost/test1');

응용 프로그램에 이미 그런 것이 있다고 생각합니다 ...


다음으로, 우리의 새로운 My_Doctrine_Record 수업 :

class My_Doctrine_Record extends Doctrine_Record
{
    public function getErrorStackAsString()
    {
        $errorStack = $this->getErrorStack();
        if (count($errorStack)) {
            $message = sprintf("BAD DATA in class %s :\n", get_class($this));
            foreach ($errorStack as $field => $errors) {
                $messageForField = $this->_getValidationFailed($field, $errors);
                if ($messageForField === null) {
                    // No custom message for this case => we use the default one.
                    $message .= "    * " . count($errors) . " validator" . (count($errors) > 1 ?  's' : null) . " failed on $field (" . implode(", ", $errors) . ")\n";
                } else {
                    $message .= "    * " . $messageForField;
                }
            }
            return $message;
        } else {
            return false;
        }
    }

    protected function _getValidationFailed($field, $errors) {
        return null;
    }

}

당신은 그것을 알게 될 것입니다 getErrorStackAsString 방법은 교리가 제공 한 것들에 의해 수행 된 일에서 영감을 받았습니다. 이것은 정상적인 것 같습니다.

눈에 띄는 또 다른 것 :

  • _을 정의하고 호출합니다.getValidationFailed 방법
  • 오류 메시지를 생성해야합니다. 또는 반환 null 기본 Behabiour를 사용하려는 경우
  • 그리고 우리는 그것을 과부하시킬 수 있습니다 _getValidationFailed 모델 클래스의 메소드, 물건을 사용자 정의합니다 ;-)


그리고 이제 내 모델 클래스 :

class Test extends My_Doctrine_Record
{
    protected function _getValidationFailed($field, $errors) {
        switch ($field) {
            case 'name': 
                    return "You entered wrong data from 'name' field.\n      Errors are for '" 
                        . implode("', '", $errors) . "'\n";
                break;
            // other fields ?
            default:
                return null;
        }
    }

    public function setTableDefinition()
    {
        $this->setTableName('test');
        $this->hasColumn('id', 'integer', 4, array(
             'type' => 'integer',
             'length' => 4,
             'unsigned' => 0,
             'primary' => true,
             'autoincrement' => true,
             ));
        $this->hasColumn('name', 'string', 32, array(
             'type' => 'string',
             'length' => 32,
             'fixed' => false,
             'notnull' => true,
             'email'   => true,
             ));
        $this->hasColumn('value', 'string', 128, array(
             'type' => 'string',
             'length' => 128,
             'fixed' => false,
             'notnull' => true,
             'htmlcolor' => true,
             ));
        $this->hasColumn('date_field', 'integer', 4, array(
             'type' => 'timestamp',
             'notnull' => true,
             ));
    }
}

확장됩니다 My_Doctrine_Record, 그리고 정의 a _getValidationFailed 메소드는 name 내 모델의 분야.


이제 레코드를로드하기 위해 그렇게한다고 가정 해 봅시다.

$test = Doctrine::getTable('Test')->find(1);
var_dump($test->toArray());

"나쁜"값을 설정하고 수정하려고 시도해 봅시다.

$test->name = (string)time();
$test->value = 'glop';
try {
    $test->save();
} catch (Doctrine_Validator_Exception $e) {
    echo '<pre>';
    echo $e->getMessage();
    echo '</pre>';
    die;
}

둘 다 name 그리고 value 필드는 괜찮지 않습니다 ... 따라서 검증 방법을 살펴 보고이 오류 메시지를 생성합니다.

BAD DATA in class Test :
    * You entered wrong data from 'name' field.
      Errors are for 'email'
    * 1 validator failed on value (htmlcolor)

""메시지를 볼 수 있습니다.name"맞춤화되었고"value"기본 교리에서 나옵니다.


결론적으로 : 쉽지는 않지만 가능합니다. ;-)

그리고 이제 문제에 대한 정확한 해결책에 대한 가이드로 이것을 사용하는 것은 당신에게 달려 있습니다. :-)
더 코딩이 필요할 것입니다.하지만 당신은 실제 거래에서 멀지 않습니다!

재미있게 보내세요!

다른 팁

현재 버전에서는 불가능합니다 !!!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top