Yii2: Can I create rules and custom error messages that apply when DELETING a model?How to set a flash message in Yii2?Yii2 model custom rules and validations for attribute which is arrayYii2 Access Rules Using Different ModelsIgnore validation on soft deleted modelsYii2, Custom validation message with attribute namesYii2 rule not being appliedYii2 Model Rules Update Checking Rules For Same RecordDeleting related models in yii2Yii2: model rules inheritance on behavioryii2 custom error message for 'minHeight' ruleYii2: validation errors that are not attribute specific

Multi tool use
Multi tool use

Lay out the Carpet

Can the discrete variable be a negative number?

A Rare Riley Riddle

I'm in charge of equipment buying but no one's ever happy with what I choose. How to fix this?

Unreliable Magic - Is it worth it?

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

What is the intuitive meaning of having a linear relationship between the logs of two variables?

Is there a korbon needed for conversion?

Term for the "extreme-extension" version of a straw man fallacy?

Class Action - which options I have?

Implement the Thanos sorting algorithm

Arithmetic mean geometric mean inequality unclear

How did Arya survive the stabbing?

Is HostGator storing my password in plaintext?

How can I kill an app using Terminal?

Is there a good way to store credentials outside of a password manager?

Avoiding estate tax by giving multiple gifts

Is a stroke of luck acceptable after a series of unfavorable events?

Escape a backup date in a file name

What does "I’d sit this one out, Cap," imply or mean in the context?

How to be diplomatic in refusing to write code that breaches the privacy of our users

Large drywall patch supports

Why does indent disappear in lists?



Yii2: Can I create rules and custom error messages that apply when DELETING a model?


How to set a flash message in Yii2?Yii2 model custom rules and validations for attribute which is arrayYii2 Access Rules Using Different ModelsIgnore validation on soft deleted modelsYii2, Custom validation message with attribute namesYii2 rule not being appliedYii2 Model Rules Update Checking Rules For Same RecordDeleting related models in yii2Yii2: model rules inheritance on behavioryii2 custom error message for 'minHeight' ruleYii2: validation errors that are not attribute specific













2















I want to delete a model but it might have related records in another model when will prohibit me doing so. How can I best use the already defined relationships to check if delete will be successful? Potentially there could also be non-relationship reasons for not allowing a delete.



Once I have determined my error messages how can I best store them and pass them on to the front-end? beforeDelete() only returns true or false but I of course need to provide user with friendly error messages saying WHY the record can't be deleted...



Relationship already defined is for example:



public function getPhonenumbers() 
return $this->hasMany(Phonenumber::class, ['ph_contactID' => 'contactID']);










share|improve this question






















  • please give your actionDelete() code.

    – vishuB
    Mar 8 at 11:47











  • Might want to checkout transactions? yiiframework.com/doc/api/2.0/yii-db-transaction

    – Miaan
    Mar 8 at 13:05
















2















I want to delete a model but it might have related records in another model when will prohibit me doing so. How can I best use the already defined relationships to check if delete will be successful? Potentially there could also be non-relationship reasons for not allowing a delete.



Once I have determined my error messages how can I best store them and pass them on to the front-end? beforeDelete() only returns true or false but I of course need to provide user with friendly error messages saying WHY the record can't be deleted...



Relationship already defined is for example:



public function getPhonenumbers() 
return $this->hasMany(Phonenumber::class, ['ph_contactID' => 'contactID']);










share|improve this question






















  • please give your actionDelete() code.

    – vishuB
    Mar 8 at 11:47











  • Might want to checkout transactions? yiiframework.com/doc/api/2.0/yii-db-transaction

    – Miaan
    Mar 8 at 13:05














2












2








2








I want to delete a model but it might have related records in another model when will prohibit me doing so. How can I best use the already defined relationships to check if delete will be successful? Potentially there could also be non-relationship reasons for not allowing a delete.



Once I have determined my error messages how can I best store them and pass them on to the front-end? beforeDelete() only returns true or false but I of course need to provide user with friendly error messages saying WHY the record can't be deleted...



Relationship already defined is for example:



public function getPhonenumbers() 
return $this->hasMany(Phonenumber::class, ['ph_contactID' => 'contactID']);










share|improve this question














I want to delete a model but it might have related records in another model when will prohibit me doing so. How can I best use the already defined relationships to check if delete will be successful? Potentially there could also be non-relationship reasons for not allowing a delete.



Once I have determined my error messages how can I best store them and pass them on to the front-end? beforeDelete() only returns true or false but I of course need to provide user with friendly error messages saying WHY the record can't be deleted...



Relationship already defined is for example:



public function getPhonenumbers() 
return $this->hasMany(Phonenumber::class, ['ph_contactID' => 'contactID']);







php yii2 delete-row yii2-model






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 11:34









TheStoryCoderTheStoryCoder

1,11721242




1,11721242












  • please give your actionDelete() code.

    – vishuB
    Mar 8 at 11:47











  • Might want to checkout transactions? yiiframework.com/doc/api/2.0/yii-db-transaction

    – Miaan
    Mar 8 at 13:05


















  • please give your actionDelete() code.

    – vishuB
    Mar 8 at 11:47











  • Might want to checkout transactions? yiiframework.com/doc/api/2.0/yii-db-transaction

    – Miaan
    Mar 8 at 13:05

















please give your actionDelete() code.

– vishuB
Mar 8 at 11:47





please give your actionDelete() code.

– vishuB
Mar 8 at 11:47













Might want to checkout transactions? yiiframework.com/doc/api/2.0/yii-db-transaction

– Miaan
Mar 8 at 13:05






Might want to checkout transactions? yiiframework.com/doc/api/2.0/yii-db-transaction

– Miaan
Mar 8 at 13:05













2 Answers
2






active

oldest

votes


















1














From the answers of @vishuB and @rob006 I got ideas for coming up with my own solution which I think will be superior as I can provide multiple error messages, it can be used in an API as well, and it doesn't rely on try/catching exceptions:



public function beforeDelete() 
if (!parent::beforeDelete())
$this->addError('contactID', 'For some unknown reason we could not delete this record.');


if (!empty($this->phonenumbers))
$this->addError('contactID', 'Contact is linked to a used phone number and cannot be deleted.');


if ($some_other_validation_fails)
$this->addError('contactID', 'Contact cannot be deleted because it is more than two months old.');


return ($this->hasErrors() ? false : true);



Then in my action I do this:



$contact = Contact::findOne($contactID);
if (!$contact->delete())
return $contact->getErrors(); //or use flash messages and redirect to page if you prefer

return true;





share|improve this answer






























    1














    You can throw exception in beforeDelete() with error message, and catch it in controller.



    public function beforeDelete() 
    if ($this->getPhonenumbers()->exist())
    throw new DeleteFailException('Records with phone numbers cannot be deleted.');


    return parent::beforeDelete();



    And in controller action:



    try 
    $model->delete();
    catch (DeleteFailException $esception)
    Yii::$app->session->setFlash('error', $exception->getMessage());






    share|improve this answer




















    • 1





      One would have to define the DeleteFailException exception class first though.

      – TheStoryCoder
      Mar 11 at 9:25










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55062418%2fyii2-can-i-create-rules-and-custom-error-messages-that-apply-when-deleting-a-mo%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    From the answers of @vishuB and @rob006 I got ideas for coming up with my own solution which I think will be superior as I can provide multiple error messages, it can be used in an API as well, and it doesn't rely on try/catching exceptions:



    public function beforeDelete() 
    if (!parent::beforeDelete())
    $this->addError('contactID', 'For some unknown reason we could not delete this record.');


    if (!empty($this->phonenumbers))
    $this->addError('contactID', 'Contact is linked to a used phone number and cannot be deleted.');


    if ($some_other_validation_fails)
    $this->addError('contactID', 'Contact cannot be deleted because it is more than two months old.');


    return ($this->hasErrors() ? false : true);



    Then in my action I do this:



    $contact = Contact::findOne($contactID);
    if (!$contact->delete())
    return $contact->getErrors(); //or use flash messages and redirect to page if you prefer

    return true;





    share|improve this answer



























      1














      From the answers of @vishuB and @rob006 I got ideas for coming up with my own solution which I think will be superior as I can provide multiple error messages, it can be used in an API as well, and it doesn't rely on try/catching exceptions:



      public function beforeDelete() 
      if (!parent::beforeDelete())
      $this->addError('contactID', 'For some unknown reason we could not delete this record.');


      if (!empty($this->phonenumbers))
      $this->addError('contactID', 'Contact is linked to a used phone number and cannot be deleted.');


      if ($some_other_validation_fails)
      $this->addError('contactID', 'Contact cannot be deleted because it is more than two months old.');


      return ($this->hasErrors() ? false : true);



      Then in my action I do this:



      $contact = Contact::findOne($contactID);
      if (!$contact->delete())
      return $contact->getErrors(); //or use flash messages and redirect to page if you prefer

      return true;





      share|improve this answer

























        1












        1








        1







        From the answers of @vishuB and @rob006 I got ideas for coming up with my own solution which I think will be superior as I can provide multiple error messages, it can be used in an API as well, and it doesn't rely on try/catching exceptions:



        public function beforeDelete() 
        if (!parent::beforeDelete())
        $this->addError('contactID', 'For some unknown reason we could not delete this record.');


        if (!empty($this->phonenumbers))
        $this->addError('contactID', 'Contact is linked to a used phone number and cannot be deleted.');


        if ($some_other_validation_fails)
        $this->addError('contactID', 'Contact cannot be deleted because it is more than two months old.');


        return ($this->hasErrors() ? false : true);



        Then in my action I do this:



        $contact = Contact::findOne($contactID);
        if (!$contact->delete())
        return $contact->getErrors(); //or use flash messages and redirect to page if you prefer

        return true;





        share|improve this answer













        From the answers of @vishuB and @rob006 I got ideas for coming up with my own solution which I think will be superior as I can provide multiple error messages, it can be used in an API as well, and it doesn't rely on try/catching exceptions:



        public function beforeDelete() 
        if (!parent::beforeDelete())
        $this->addError('contactID', 'For some unknown reason we could not delete this record.');


        if (!empty($this->phonenumbers))
        $this->addError('contactID', 'Contact is linked to a used phone number and cannot be deleted.');


        if ($some_other_validation_fails)
        $this->addError('contactID', 'Contact cannot be deleted because it is more than two months old.');


        return ($this->hasErrors() ? false : true);



        Then in my action I do this:



        $contact = Contact::findOne($contactID);
        if (!$contact->delete())
        return $contact->getErrors(); //or use flash messages and redirect to page if you prefer

        return true;






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 12:44









        TheStoryCoderTheStoryCoder

        1,11721242




        1,11721242























            1














            You can throw exception in beforeDelete() with error message, and catch it in controller.



            public function beforeDelete() 
            if ($this->getPhonenumbers()->exist())
            throw new DeleteFailException('Records with phone numbers cannot be deleted.');


            return parent::beforeDelete();



            And in controller action:



            try 
            $model->delete();
            catch (DeleteFailException $esception)
            Yii::$app->session->setFlash('error', $exception->getMessage());






            share|improve this answer




















            • 1





              One would have to define the DeleteFailException exception class first though.

              – TheStoryCoder
              Mar 11 at 9:25















            1














            You can throw exception in beforeDelete() with error message, and catch it in controller.



            public function beforeDelete() 
            if ($this->getPhonenumbers()->exist())
            throw new DeleteFailException('Records with phone numbers cannot be deleted.');


            return parent::beforeDelete();



            And in controller action:



            try 
            $model->delete();
            catch (DeleteFailException $esception)
            Yii::$app->session->setFlash('error', $exception->getMessage());






            share|improve this answer




















            • 1





              One would have to define the DeleteFailException exception class first though.

              – TheStoryCoder
              Mar 11 at 9:25













            1












            1








            1







            You can throw exception in beforeDelete() with error message, and catch it in controller.



            public function beforeDelete() 
            if ($this->getPhonenumbers()->exist())
            throw new DeleteFailException('Records with phone numbers cannot be deleted.');


            return parent::beforeDelete();



            And in controller action:



            try 
            $model->delete();
            catch (DeleteFailException $esception)
            Yii::$app->session->setFlash('error', $exception->getMessage());






            share|improve this answer















            You can throw exception in beforeDelete() with error message, and catch it in controller.



            public function beforeDelete() 
            if ($this->getPhonenumbers()->exist())
            throw new DeleteFailException('Records with phone numbers cannot be deleted.');


            return parent::beforeDelete();



            And in controller action:



            try 
            $model->delete();
            catch (DeleteFailException $esception)
            Yii::$app->session->setFlash('error', $exception->getMessage());







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 9 at 6:54

























            answered Mar 8 at 12:27









            rob006rob006

            10.8k31436




            10.8k31436







            • 1





              One would have to define the DeleteFailException exception class first though.

              – TheStoryCoder
              Mar 11 at 9:25












            • 1





              One would have to define the DeleteFailException exception class first though.

              – TheStoryCoder
              Mar 11 at 9:25







            1




            1





            One would have to define the DeleteFailException exception class first though.

            – TheStoryCoder
            Mar 11 at 9:25





            One would have to define the DeleteFailException exception class first though.

            – TheStoryCoder
            Mar 11 at 9:25

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55062418%2fyii2-can-i-create-rules-and-custom-error-messages-that-apply-when-deleting-a-mo%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            KO4TM6Xj26h,BNMy0y16ccUhEO689QZkUG4KmuZ 9BPfy,k Fut PjpQ
            6oCJxKHvL kt koY,JWjGL46klepQTtN4AsyvqMN,wPO,Fn Nojls9dpcvJ67BW mgFe2HM6WZWn,YZt5czDxNA50

            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            How to get text form Clipboard with JavaScript in Firefox 56?How to validate an email address in JavaScript?How do JavaScript closures work?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I copy to the clipboard in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?