Yii2 ActiveForm通过parseJSON展示decimal(15,2)格式数据问询
Got it, let's walk through how to get that decimal(15,2) data from Model B into your ActiveForm A using parseJSON(). Here's a tailored, step-by-step implementation:
1. Add AJAX Listener to Your Select2 Dropdown
Right after your existing Select2 widget, add this JavaScript to trigger a data fetch when the budget selection changes:
<?php $this->registerJs(" $('#code').on('change', function() { const budgetId = $(this).val(); if (budgetId) { $.ajax({ url: '" . Url::to(['get-budget-decimal']) . "', type: 'GET', data: {id: budgetId}, success: function(data) { // Parse the JSON response into a usable object const decimalData = JSON.parse(data); // Update your form field with the properly formatted decimal // Replace 'yourmodel-decimal_field' with your actual input ID $('#yourmodel-decimal_field').val(decimalData.formatted_value); // Use raw_value if you need the numeric value for calculations // console.log(decimalData.raw_value); }, error: () => $('#yourmodel-decimal_field').val('') }); } else { $('#yourmodel-decimal_field').val(''); } }); "); ?>
Don’t forget to replace yourmodel-decimal_field with the actual ID of the input in your ActiveForm where you want to display the decimal data.
2. Create a Controller Action to Fetch Model B Data
Add this action to your controller to retrieve the decimal data from Model B and return it as JSON:
public function actionGetBudgetDecimal($id) { // Replace Budget with your actual Model B class $modelB = Budget::findOne($id); if ($modelB) { // Replace 'decimal_column' with your Model B decimal(15,2) column name $rawDecimal = $modelB->decimal_column; // Format to match decimal(15,2) requirements $formattedDecimal = number_format($rawDecimal, 2, '.', ''); // Return both raw and formatted values for flexibility return json_encode([ 'raw_value' => (float)$rawDecimal, 'formatted_value' => $formattedDecimal ]); } return json_encode([]); }
3. Configure Your ActiveForm Field
Make sure your form field is set up to accept and display decimal values correctly:
<?= $form->field($model, 'decimal_field')->textInput([ 'type' => 'number', 'step' => '0.01', 'placeholder' => 'e.g., 1234567890123.45' ]) ?>
Using type='number' with step='0.01' ensures browsers enforce the 2-decimal format, which aligns with your decimal(15,2) data type.
Quick Validation Tip
Add a rule to Model A to validate the incoming decimal data matches your required format:
public function rules() { return [ ['decimal_field', 'number', 'numberPattern' => '/^\d{1,13}(\.\d{1,2})?$/'], // Add other rules here ]; }
This rule ensures the value stays within the 15-digit total and 2 decimal places constraint.
内容的提问来源于stack exchange,提问作者Chonjaroen Chauynoo

