Laravel 将视图字段输入数据传递给控制器​​,然后在禁用字段中返回计算值

发布于 2025-01-15 03:26:54 字数 1243 浏览 0 评论 0原文

所以我想要做的是从用户输入中获取值,然后使用方法在控制器内对其进行一些计算,并且该方法返回值将显示在下面的字段中,并带有禁用属性,该属性将在表单提交时传递到数据库。所以我的想法是:

            <input class="form-control {{ $errors->has('price') ? 'is-invalid' : '' }}" type="number" name="price" id="price" value="{{ old('price', '') }}" step="0.001" required>
            <input class="form-control {{ $errors->has('quantity') ? 'is-invalid' : '' }}" type="number" name="quantity" id="quantity" value="{{ old('quantity', '') }}" step="0.001" required>
            <input class="form-control {{ $errors->has('other_expenses') ? 'is-invalid' : '' }}" type="number" name="other_expenses" id="other_expenses" value="{{ old('other_expenses', '') }}" step="0.01" required>
            <input class="form-control {{ $errors->has('coefficient') ? 'is-invalid' : '' }}" type="number" name="coefficient" id="coefficient" value="{{ old('coefficient', '') }}" step="0.001" required>
            <input class="form-control {{ $errors->has('total') ? 'is-invalid' : '' }}" type="number" name="total" id="total" value="{{ old('total', '') }}" step="0.001" disabled>

然后我想通过控制器进行一些计算并在“总计”字段中返回一些值。 所以在我的控制器中我应该接受 tada 然后计算如下: 总计 = (价格数量other_expenses)*系数

So what i want to do is take values from user input, then do some calculation with it inside the controller with method and that method return value to be displayed in field below with disabled attribute that will on form submit be passed to database. So what i have in view is:

            <input class="form-control {{ $errors->has('price') ? 'is-invalid' : '' }}" type="number" name="price" id="price" value="{{ old('price', '') }}" step="0.001" required>
            <input class="form-control {{ $errors->has('quantity') ? 'is-invalid' : '' }}" type="number" name="quantity" id="quantity" value="{{ old('quantity', '') }}" step="0.001" required>
            <input class="form-control {{ $errors->has('other_expenses') ? 'is-invalid' : '' }}" type="number" name="other_expenses" id="other_expenses" value="{{ old('other_expenses', '') }}" step="0.01" required>
            <input class="form-control {{ $errors->has('coefficient') ? 'is-invalid' : '' }}" type="number" name="coefficient" id="coefficient" value="{{ old('coefficient', '') }}" step="0.001" required>
            <input class="form-control {{ $errors->has('total') ? 'is-invalid' : '' }}" type="number" name="total" id="total" value="{{ old('total', '') }}" step="0.001" disabled>

And then i want to do some calculation through controller and return some value in "total" field.
So in my controller i should accept that tada and then calculate something like:
total = (pricequantityother_expenses)*coefficient

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉城 2025-01-22 03:26:54

从上面的代码来看,计算所需的一切似乎都在表单上。控制器上是否发生了特定操作?

例如,如果您打算计算的只是总计 = (价格 * 数量 * other_expenses ) * 系数,则您可能不一定需要将数据发送到控制器。

您可以使用Alpine js直接在页面上执行计算。

请按照以下步骤操作:

  1. 在布局中包含 alpine
    <脚本延迟 src="https://unpkg.com/[电子邮件受保护]/dist/cdn.min.js">

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
<div x-data="{
              price: parseInt( '120'), 
              quantity: parseInt( '5'), 
              other_expenses: parseInt( '50'),
              coefficient: parseInt( '2') 
            }">
    <input type="number" name="price" x-model.number="price"  />
    <input type="number" name="quantity" x-model.number="quantity" />
    <input type="number" name="other_expenses" x-model.number="other_expenses" />
    <input type="number" name="coefficient" x-model.number="coefficient" />
    <input type="text" x-bind:value="price * quantity * other_expenses * coefficient" name="total" disabled />
</div>

注意:您可以像这样传递旧值 price: parseInt( '{{ old('price') }}')

您可以提交,并且应该提交总计。

如果必须使用控制器进行计算,则可能必须将 ajax 与 vuejs 或 jquery 结合使用。

更新:对于 ajax 实现,您可以使用 alpine 'fetch' 对后端进行 API 调用以进行任何验证。

<div x-data="{
    price: parseInt( '120'), 
    quantity: parseInt( '5'), 
    other_expenses: parseInt( '50'),
    coefficient: parseInt( '2') ,
    data: null,
    calculateTotal() {
            fetch('/calculateTotal/route/url',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    price: this.price,
                    quantity: this.quantity,
                    other_expenses:this.other_expenses,
                    coefficient:this.coefficient
                }),
            })
            .then(response => response.json())
            .then(data => {
                    this.data = data
                    console.log(data)

            })
            .catch(error => {
                    console.log({ error })
                });
    }">
<input type="number" name="price" x-model.number="price"  @keyup.debounce.750ms="calculateTotal()"  />
<input type="number" name="quantity" x-model.number="quantity" @keyup.debounce.750ms="calculateTotal()" />
<input type="number" name="other_expenses" x-model.number="other_expenses" @keyup.debounce.750ms="calculateTotal()" />
<input type="number" name="coefficient" x-model.number="coefficient" @keyup.debounce.750ms="calculateTotal()" />

<input type="text" x-bind:value="data.total" name="total" readonly />

//Your web.php or api.php depending on where the 
Route::post('gettotal', 'ProductController@getTotal');

//Controller
public function getTotal(Request $request)
{
    $data = [
        'total' => $request->price * $request->quantity * $request->other_expenses * $request->coefficient; //You can include any validation here
    ];
    return response()->json($data)
}

From your code above, it looks like everything you need for the calculation is there on the form. Is there a particular action that happens on the controller?

For example, if all you need you intend to calculate is total = (price * quantity * other_expenses ) * coefficient, you may not necessarily need to send the data to the controller.

You can use Alpine js to perform the calculation right on the page.

Follow the step below:

  1. Include alpine in your layout
    <script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
<div x-data="{
              price: parseInt( '120'), 
              quantity: parseInt( '5'), 
              other_expenses: parseInt( '50'),
              coefficient: parseInt( '2') 
            }">
    <input type="number" name="price" x-model.number="price"  />
    <input type="number" name="quantity" x-model.number="quantity" />
    <input type="number" name="other_expenses" x-model.number="other_expenses" />
    <input type="number" name="coefficient" x-model.number="coefficient" />
    <input type="text" x-bind:value="price * quantity * other_expenses * coefficient" name="total" disabled />
</div>

Note: You can pass the old values like so price: parseInt( '{{ old('price') }}')

You can submit and the total should be submitted.

If you must use the controller for the calculations, you may have to use ajax with vuejs or jquery.

UPDATE: For the ajax implementation, you can use alpine 'fetch' to make API call to the backend for any validation.

<div x-data="{
    price: parseInt( '120'), 
    quantity: parseInt( '5'), 
    other_expenses: parseInt( '50'),
    coefficient: parseInt( '2') ,
    data: null,
    calculateTotal() {
            fetch('/calculateTotal/route/url',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    price: this.price,
                    quantity: this.quantity,
                    other_expenses:this.other_expenses,
                    coefficient:this.coefficient
                }),
            })
            .then(response => response.json())
            .then(data => {
                    this.data = data
                    console.log(data)

            })
            .catch(error => {
                    console.log({ error })
                });
    }">
<input type="number" name="price" x-model.number="price"  @keyup.debounce.750ms="calculateTotal()"  />
<input type="number" name="quantity" x-model.number="quantity" @keyup.debounce.750ms="calculateTotal()" />
<input type="number" name="other_expenses" x-model.number="other_expenses" @keyup.debounce.750ms="calculateTotal()" />
<input type="number" name="coefficient" x-model.number="coefficient" @keyup.debounce.750ms="calculateTotal()" />

<input type="text" x-bind:value="data.total" name="total" readonly />

//Your web.php or api.php depending on where the 
Route::post('gettotal', 'ProductController@getTotal');

//Controller
public function getTotal(Request $request)
{
    $data = [
        'total' => $request->price * $request->quantity * $request->other_expenses * $request->coefficient; //You can include any validation here
    ];
    return response()->json($data)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文