Calculo de total automaticamente

Hola amigos,

Tengo un formulario para crear una factura, donde primero selcciono el producto, luego la cantidad , y quisisera que el campo total se calcule de manera automatica una vez completados los campos anteriores.

Adjunto la imagen del formulario para que se entienda mejor.

Desde ya muchas gracias.

Puedes escribir tu codigo del controlador y la vista donde quieres hacer la operacion

aqui va el controlador:

public function behaviors()


{


	return [


    	'access' => [


        	'class' => AccessControl::className(),


        	'rules' => [


            	[


                	'actions' => ['index','create','update','delete','view'],


                	'allow' => true,


                	'roles' => ['@'],


            	],


        	],


    	],





    	'verbs' => [


        	'class' => VerbFilter::className(),


        	'actions' => [


            	'delete' => ['POST'],


        	],


    	],


	];


}





/**


* Lists all Facturas models.


* @return mixed


*/


public function actionIndex()


{


	$searchModel = new FacturasSearch();


	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);





	return $this->render('index', [


    	'searchModel' => $searchModel,


    	'dataProvider' => $dataProvider,


	]);


}





/**


* Displays a single Facturas model.


* @param integer $id


* @return mixed


*/


public function actionView($id)


{


	return $this->render('view', [


    	'model' => $this->findModel($id),


	]);


}





/**


* Creates a new Facturas model.


* If creation is successful, the browser will be redirected to the 'view' page.


* @return mixed


*/


public function actionCreate()


{


	$model = new Facturas();





	if ($model->load(Yii::$app->request->post()) && $model->save()) {


    	return $this->redirect(['index']);


	} else {


    	return $this->render('create', [


        	'model' => $model,


    	]);


	}


}





/**


* Updates an existing Facturas model.


* If update is successful, the browser will be redirected to the 'view' page.


* @param integer $id


* @return mixed


*/


public function actionUpdate($id)


{


	$model = $this->findModel($id);





	if ($model->load(Yii::$app->request->post()) && $model->save()) {


    	return $this->redirect(['index']);


	} else {


    	return $this->render('update', [


        	'model' => $model,


    	]);


	}


}





/**


* Deletes an existing Facturas model.


* If deletion is successful, the browser will be redirected to the 'index' page.


* @param integer $id


* @return mixed


*/


public function actionDelete($id)


{


	$this->findModel($id)->delete();





	return $this->redirect(['index']);


}





/**


* Finds the Facturas model based on its primary key value.


* If the model is not found, a 404 HTTP exception will be thrown.


* @param integer $id


* @return Facturas the loaded model


* @throws NotFoundHttpException if the model cannot be found


*/


protected function findModel($id)


{


	if (($model = Facturas::findOne($id)) !== null) {


    	return $model;


	} else {


    	throw new NotFoundHttpException('The requested page does not exist.');


	}


}

}

VISTA;

<div class="facturas-form">

&lt;?php &#036;form = ActiveForm::begin(); ?&gt;





&lt;?php echo &#036;form-&gt;field(&#036;model, 'Fecha')-&gt;widget (&#092;yii&#092;jui&#092;DatePicker::classname(), [


    	'dateFormat' =&gt; 'dd-MM-yyyy',


    	'value' =&gt; date('d/m/y'),


    	'options' =&gt; ['style' =&gt; 'position: relative; z-index:999', 'class' =&gt; 'form-control','placeholder'=&gt;'Haga click para seleccionar fecha']


	]) 


?&gt;


&lt;?php 





echo &#036;form-&gt;field(&#036;model, 'Hora')-&gt;widget(kartik&#092;time&#092;TimePicker::classname(),[  


        	'pluginOptions' =&gt; [


        	'showSeconds' =&gt; true,


        	'showMeridian' =&gt; false,


        	'minuteStep' =&gt; 1,


        	//'secondStep' =&gt; 5,


    	]


        	]) 


?&gt;


&lt;?php


&#036;perfumes = ArrayHelper::map(Perfumes::find()-&gt;where(['Stock' =&gt;1])-&gt;orderBy('NombrePerfume')-&gt;all(),'NombrePerfume','NombrePerfume','Tamanio');


echo &#036;form-&gt;field(&#036;model,'Producto')-&gt;widget(Select2::classname(), [


	'data' =&gt;&#036;perfumes, 


	'language' =&gt; 'es', 


	'options' =&gt; ['placeholder' =&gt; 'Seleccione un perfume...'],


	'pluginOptions' =&gt; ['allowClear' =&gt;true],


	]);


?&gt;

<?= $form->field($model, ‘Cantidad’)->textInput([‘placeholder’=>‘Ingrese una cantidad (SOLO NUMERICO)…’]) ?>

&lt;?php 


echo &#036;form-&gt;field(&#036;model, 'Total')-&gt;widget(MaskMoney::classname(),


	[


    	'pluginOptions' =&gt; [


    	'prefix' =&gt; '&#036; ', 


    	'allowNegative' =&gt; false


	]


]);


?&gt;


&lt;?php


&#036;clientes = ArrayHelper::map(Clientes::find()-&gt;where(['status' =&gt;1])-&gt;orderBy('NombreCliente')-&gt;all(),'idCliente','NombreCliente');


echo &#036;form-&gt;field(&#036;model,'idCliente')-&gt;widget(Select2::classname(), [


	'data' =&gt;&#036;clientes, 


	'language' =&gt; 'es', 


	'options' =&gt; ['placeholder' =&gt; 'Seleccione un cliente...'],


	'pluginOptions' =&gt; ['allowClear' =&gt;true],


	]);


?&gt;


&lt;?= &#036;form-&gt;field(&#036;model, 'Comentario')-&gt;textArea(['placeholder'=&gt;'Escriba un comentario...','maxlength' =&gt; true]) ?&gt;





&lt;div class=&quot;form-group&quot;&gt;


	&lt;?= Html::submitButton(&#036;model-&gt;isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' =&gt; &#036;model-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?&gt;


&lt;/div&gt;





&lt;?php ActiveForm::end(); ?&gt;

</div>

aqui va el controlador:

public function behaviors()


{


	return [


    	'access' =&gt; [


        	'class' =&gt; AccessControl::className(),


        	'rules' =&gt; [


            	[


                	'actions' =&gt; ['index','create','update','delete','view'],


                	'allow' =&gt; true,


                	'roles' =&gt; ['@'],


            	],


        	],


    	],





    	'verbs' =&gt; [


        	'class' =&gt; VerbFilter::className(),


        	'actions' =&gt; [


            	'delete' =&gt; ['POST'],


        	],


    	],


	];


}





/**


* Lists all Facturas models.


* @return mixed


*/


public function actionIndex()


{


	&#036;searchModel = new FacturasSearch();


	&#036;dataProvider = &#036;searchModel-&gt;search(Yii::&#036;app-&gt;request-&gt;queryParams);





	return &#036;this-&gt;render('index', [


    	'searchModel' =&gt; &#036;searchModel,


    	'dataProvider' =&gt; &#036;dataProvider,


	]);


}





/**


* Displays a single Facturas model.


* @param integer &#036;id


* @return mixed


*/


public function actionView(&#036;id)


{


	return &#036;this-&gt;render('view', [


    	'model' =&gt; &#036;this-&gt;findModel(&#036;id),


	]);


}





/**


* Creates a new Facturas model.


* If creation is successful, the browser will be redirected to the 'view' page.


* @return mixed


*/


public function actionCreate()


{


	&#036;model = new Facturas();





	if (&#036;model-&gt;load(Yii::&#036;app-&gt;request-&gt;post()) &amp;&amp; &#036;model-&gt;save()) {


    	return &#036;this-&gt;redirect(['index']);


	} else {


    	return &#036;this-&gt;render('create', [


        	'model' =&gt; &#036;model,


    	]);


	}


}





/**


* Updates an existing Facturas model.


* If update is successful, the browser will be redirected to the 'view' page.


* @param integer &#036;id


* @return mixed


*/


public function actionUpdate(&#036;id)


{


	&#036;model = &#036;this-&gt;findModel(&#036;id);





	if (&#036;model-&gt;load(Yii::&#036;app-&gt;request-&gt;post()) &amp;&amp; &#036;model-&gt;save()) {


    	return &#036;this-&gt;redirect(['index']);


	} else {


    	return &#036;this-&gt;render('update', [


        	'model' =&gt; &#036;model,


    	]);


	}


}





/**


* Deletes an existing Facturas model.


* If deletion is successful, the browser will be redirected to the 'index' page.


* @param integer &#036;id


* @return mixed


*/


public function actionDelete(&#036;id)


{


	&#036;this-&gt;findModel(&#036;id)-&gt;delete();





	return &#036;this-&gt;redirect(['index']);


}





/**


* Finds the Facturas model based on its primary key value.


* If the model is not found, a 404 HTTP exception will be thrown.


* @param integer &#036;id


* @return Facturas the loaded model


* @throws NotFoundHttpException if the model cannot be found


*/


protected function findModel(&#036;id)


{


	if ((&#036;model = Facturas::findOne(&#036;id)) &#33;== null) {


    	return &#036;model;


	} else {


    	throw new NotFoundHttpException('The requested page does not exist.');


	}


}

}

VISTA;

<div class="facturas-form">

&lt;?php &#036;form = ActiveForm::begin(); ?&gt;





&lt;?php echo &#036;form-&gt;field(&#036;model, 'Fecha')-&gt;widget (&#092;yii&#092;jui&#092;DatePicker::classname(), [


    	'dateFormat' =&gt; 'dd-MM-yyyy',


    	'value' =&gt; date('d/m/y'),


    	'options' =&gt; ['style' =&gt; 'position: relative;  z-index:999', 'class' =&gt; 'form-control','placeholder'=&gt;'Haga click  para seleccionar fecha']


	]) 


?&gt;


&lt;?php 





echo &#036;form-&gt;field(&#036;model, 'Hora')-&gt;widget(kartik&#092;time&#092;TimePicker::classname(),[  


        	'pluginOptions' =&gt; [


        	'showSeconds' =&gt; true,


        	'showMeridian' =&gt; false,


        	'minuteStep' =&gt; 1,


        	//'secondStep' =&gt; 5,


    	]


        	]) 


?&gt;


&lt;?php


&#036;perfumes = ArrayHelper::map(Perfumes::find()-&gt;where(['Stock'  =&gt;1])-&gt;orderBy('NombrePerfume')-&gt;all(),'NombrePerfume','NombrePerfume','Tamanio');


echo &#036;form-&gt;field(&#036;model,'Producto')-&gt;widget(Select2::classname(), [


	'data' =&gt;&#036;perfumes, 


	'language' =&gt; 'es', 


	'options' =&gt; ['placeholder' =&gt; 'Seleccione un perfume...'],


	'pluginOptions' =&gt; ['allowClear' =&gt;true],


	]);


?&gt;

<?= $form->field($model, ‘Cantidad’)->textInput([‘placeholder’=>‘Ingrese una cantidad (SOLO NUMERICO)…’]) ?>

&lt;?php 


echo &#036;form-&gt;field(&#036;model, 'Total')-&gt;widget(MaskMoney::classname(),


	[


    	'pluginOptions' =&gt; [


    	'prefix' =&gt; '&#036; ', 


    	'allowNegative' =&gt; false


	]


]);


?&gt;


&lt;?php


&#036;clientes = ArrayHelper::map(Clientes::find()-&gt;where(['status'  =&gt;1])-&gt;orderBy('NombreCliente')-&gt;all(),'idCliente','NombreCliente');


echo &#036;form-&gt;field(&#036;model,'idCliente')-&gt;widget(Select2::classname(), [


	'data' =&gt;&#036;clientes, 


	'language' =&gt; 'es', 


	'options' =&gt; ['placeholder' =&gt; 'Seleccione un cliente...'],


	'pluginOptions' =&gt; ['allowClear' =&gt;true],


	]);


?&gt;


&lt;?= &#036;form-&gt;field(&#036;model,  'Comentario')-&gt;textArea(['placeholder'=&gt;'Escriba un  comentario...','maxlength' =&gt; true]) ?&gt;





&lt;div class=&quot;form-group&quot;&gt;


	&lt;?= Html::submitButton(&#036;model-&gt;isNewRecord ? Yii::t('app',  'Create') : Yii::t('app', 'Update'), ['class' =&gt;  &#036;model-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?&gt;


&lt;/div&gt;





&lt;?php ActiveForm::end(); ?&gt;

</div>

Buenas, por lo que observo en tu codigo tienes una tabla productos, donde seleccionas el producto (perfume), en el formulario tiene un campo input donde ingresas la cantidad, pero no veo los precios, que me imagino estan en la tabla productos, no veo la estructura de esta tabla, tambien me imagino que debes tener dos tablas, una para para las facturas y otra para los detalles de las factuas, en la tabla facturas debes poner, fechas, clientes, etc. y en la tabla detalles, los detalles de los productos, precios cantidad, etc, puedes ser un poco mas explicito en esta parte.

Creo que en tu controlador debes tener una funcion donde captures los detalles de los productos, donde debe estar los precios, luego con esto solo tiene que hacer mediante codigo el calculo de los importes, me imagino cantidad*precios, si no interviene ningun factor condicionante como impuestos, etc.

puede ser algo asi:

en tu controlador:




public function actionCrearFactura()

{

$importeTotal = 0; //aqui declata la variable para el importe

        $id=$_POST['modelid'];


        if($id)

        $model=$this->loadModel($id);   

        else            

        $model = new Factuas;  

        if(isset($_POST['detalle']))

        {

//aqui pones todos los detalles de la tabla factura    	

    .........

           	$model->fecha=$_POST['fecha'];

                $model->CodCliente=$_POST['cliente'];

              .....


        if ($model->save()) {


                DetallesFacturas::model()->deleteAll('Id_sal=:id', array(':id'=>$model->id));


                foreach($_POST['detalle'] as $item){


                //Insertar los detalles de la salida

                $producto= Productos::model()->find('Descripcion_producto=:postID', array(':postID'=>$item['producto'])); //	algo asi para obtener los valores de la tabla productos

                $detalle=new DetallesFacturas;      

                $detalle->Id_detalles=$model->Id_modelo;//deben estar relacionados

                $detalle->codigo=$producto->codigoproducto;

                $detalle->cantidad=$item['cantidad'];                

                $detalle->importe=$item['cantidad']*$producto->precio;

                $detalle->save(); 

               $importeTotal += $detalle->importe;//aqui sumas todos los importes para todos los productos de tu factura

                

                }

        }   			

        }

 }

....

//Luego solo tienes que pasarle este valor a la tabla factura que es donde debes guardar el importe total

 $Factura>ImporteTotalFac = $importeTotal;



de todas formas se necesita mas informacion sobre las estructura de tus tabla