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

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







            Popular posts from this blog

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page