25 Sep 2017
Currency name required only when the amount is entered
On any application development the transaction related forms shall have currency field (if the application intended to support multiple currencies), which should become mandatory only when the amount is available
Detailed Description: Yii is a high-performance PHP framework best for developing Web 2.0 applications. Yii comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc. As a rule of thumb, you should never trust the data received from end users and should always validate it before putting it to good use. To validate attributes only when certain conditions apply, e.g. the validation of one attribute depends on the value of another attribute, in transaction forms, currency name or code is mandatory if the amount is available to convert or calculate the equivalent amount in base currency.
Solution
Step -1: Open the model for which the validation is required in order to modify the rule. Assume payment as table name, and the model name should be payment.php; In the basic template, the path is app/models/payment.php; In advanced template the path is common/models/payment.php Step -2: Find function called rules() and insert the below code within return[] array. Add ',' at an appropriate place if there are existing attribute rules. Eg: if you are adding the code after the existing rule, use ',' before the code start. ['currency', 'required', //This is server side validation 'when' => function ($model) { if(empty($model->amount)) { return false; }else { //Error will thrown return true; } }, //This is for client side validation 'whenClient' => "function (attribute, amount) { if($('#model-amount').val()=='' || $('#model-amount').val()==null) { return false; }else { //Error will thrown return true; } }" ] Step -3: Now the rules will be applied in the form validation related to this model in both client side and server side.
Share this Article on
Tags: form rules, form validation, yii,
RELATED POSTS