Announcement

Collapse
No announcement yet.

Translate custom error in Exception

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Translate custom error in Exception

    Hi there! I wrote hook which check not empty field when manager change status in account entity.
    I added transated labels in my Global.json my language (uk_UA)
    PHP Code:
    {
    "errorMessages": {
    "ErrorField1Empty""Перехід на статус 2 наможливий, поле field1 не може бути порожнє.",
    "ErrorField2Empty""Перехід на статус 3 наможливий: поле field2 не може бути порожнє."
    }
    }
    ​ 
    My function which check field:

    PHP Code:
    protected $language;

    public function 
    __construct(Language $language)
    {
    $this->language $language;
    }

    public function 
    beforeSave(Entity $entity, array $options = [])
    {
    $status $entity->get('status');
    $prevStatus $entity->getFetched('status');

    if (
    $status === 'test1' && $prevStatus !== 'test1') {
    $field1 $entity->get('field1');
    if (empty(
    $field1)) {
    $message $this->language->translate('ErrorField1Empty''errorMessages');
    throw new 
    \Exception($message);
    }
    }

    if (
    $status === 'test2' && $prevStatus !== 'test2') {
    $field2 $entity->get('field2');
    if (empty(
    $field2)) {
    $message $this->language->translate('ErrorField2Empty''errorMessages');
    throw new 
    \Exception($message);
    }
    }
    }
    ​ 
    It construction works, $message got value from errorMessages, but it can't show me error on Ukrainian Language.
    Any ideas? Is It possible?
    Best wishes!

  • #2
    Use throw \Espo\Core\Exception\Error::createWithBody https://github.com/espocrm/espocrm/b.../Error.php#L49

    PHP Code:
            \Espo\Core\Exceptions\Error::createWithBody(
                
    'some-reason',
                
    \Espo\Core\Exceptions\Error\Body::create()
                    ->
    withMessageTranslation('someTranslationKey'null, [
                        
    'placeholder' => 'value',
                    ])
                    ->
    encode()
            );
    ​ 

    Translation path in a language file: messages > someTranslationKey.

    This exception will be translated in the front-end.

    {placeholder} will be replaced with 'value'.
    Last edited by yuri; 03-29-2023, 12:55 PM.

    Comment

    Working...
    X