0

In a custom validation function in my model class. I need to use javascript code. for that i used registerJs function but i am getting error:- Calling to undefined function registerJs()

I also tried calling it by including View class i.e., View::registerJs() but it is also giving error called

Non-static method yii\web\View::registerJs() should not be called statically, assuming $this from incompatible context

How can i user Javascript in Yii2 model class.

Edit: I have created a custom function for mobile number validation and calling that function from rules section of model. Now i want to use javascript code in that function. is there any other way to achive it?

Thanks in advance

Ninja Turtle
  • 1,293
  • 2
  • 24
  • 50
  • 2
    What you are trying to do is violating the MVC pattern used by Yii 2. Model should not generate parts of View and that is why there are no easy way to get to the `registerJs()` method from there. – Bizley Oct 04 '16 at 06:48
  • @Bizley. I have created a custom function for mobile number validation and calling that function from rules section of model. Now i want to use javascript code in that function. is there any other way to achive it? – Ninja Turtle Oct 04 '16 at 06:52
  • In this case please add your comment to the question for clarification. Check http://www.yiiframework.com/doc-2.0/guide-input-validation.html#using-client-side-validation for more details about adding client-side validation to model rules. – Bizley Oct 04 '16 at 06:57
  • The moment you hear yourself saying "javascript in model", you should know you're doing it wrong. – walther Oct 04 '16 at 08:42

2 Answers2

0

That method is not static. If you open the view.php of the framework you can check out the implementation.

   public function registerJs($js, $position = self::POS_READY, $key = null){..
   }

Exception clearly mentions that should not be called statically because it is not declared static.

I have seen few of the implementations which call this method as:

$view->registerJs($js, $view::POS_END);

Basically loading a particular JS file in one of the functions.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
0

It is not a good idea using Javascript with a model. If you go that way then probably after some time you will find you heading into big problems with the architecture of the app.

The best way is to call the model inside a controller and then interact with the controller through the Javascript code.