How to get sum value from different table based id relation laravel then display on view? - eloquent

I get stuck on this and i newbie on laravel :(
I can't display list of user score test.
This is my code :
My User Model :
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'username', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function test()
{
return $this->hasOne('App\Test');
}
}
My Test Model :
class Test extends Model
{
protected $fillable = [
'user_id', 'test_a', 'test_b',
];
public function user()
{
return $this->belongsTo('App\User');
}
}
My Controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Test;
use DB;
class HomeController extends Controller
{
public function index()
{
$users = User::get();
$scores = Test::with('user')
->value(DB::raw("SUM(test_a + test_b)"));
return view('home', compact('users','scores'));
}
}
My home View :
<table>
<tr>
<th>Name</th>
<th>Total Score</th>
</tr>
#foreach($users as $user)
<tr>
<td>{{ $user->username }}</td>
<td>{{ $scores }}</td>
</tr>
#endforeach
</table>
The problem is i can't display list of user and total score each user. I get eror. Anyone can help me with this??

You have to use closure to apply query on eloquent relationship. So
In HomeController.php
public function index()
{
$users = User::with(['test' => function($query){
$query->select('*', DB::raw("SUM(test_a + test_b) as scores"))
}])->get();
return view('home', compact('users'));
}
And in view
<table>
<tr>
<th>Name</th>
<th>Total Score</th>
</tr>
#foreach($users as $user)
<tr>
<td>{{ $user->username }}</td>
<td>{{ $user->test->scores }}</td> <!-- getting scores of user -->
</tr>
#endforeach
</table>

Related

Still unable with Symfony to validate collection form

I'm using SYMFONY 5 and have setup a collection form where the user is enabled to create a service and add numerous sub-services to the service. This is working fine and the user can add/edit/show/delete services and also sub-services.
Now I want to validate if a new sub-service is added and the form is submitted, the language of the sub-service item must be the one of the service item. If not, the database will not be updatet and the user will get an error message (see screen-shot). This is also working fine with one exception:
I cannot achieve to stick the error-message to the failed sub-service! It appears on every sub-service.
Here the definition of my entity service:
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\ServicesRepository")
*/
class Services
{
/**
* #ORM\Id()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=3)
*/
private $sprache;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $transid;
/**
* #ORM\Column(type="string", length=200)
*/
private $header;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $body;
/**
* #ORM\OneToMany(targetEntity="App\Entity\SubServices", mappedBy="services",cascade={"persist"})
* #Assert\Valid()
*/
private $subServices;
public function __construct()
{
$this->subServices = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id): self
{
$this->id = $id;
return $this;
}
public function getTransId(): ?int
{
return $this->transid;
}
public function setTransId(int $transid): self
{
$this->transid = $transid;
return $this;
}
public function getSprache(): ?string
{
return $this->sprache;
}
public function setSprache(string $sprache): self
{
$this->sprache = $sprache;
return $this;
}
public function getHeader(): ?string
{
return $this->header;
}
public function setHeader(string $header): self
{
$this->header = $header;
return $this;
}
public function getBody(): ?string
{
return $this->body;
}
public function setBody(?string $body): self
{
$this->body = $body;
return $this;
}
/**
* #return Collection|SubServices[]
*/
public function getSubServices(): Collection
{
return $this->subServices;
}
public function addSubService(SubServices $subService): self
{
if (!$this->subServices->contains($subService)) {
$this->subServices[] = $subService;
$subService->setServices($this);
}
return $this;
}
public function removeSubService(SubServices $subService): self
{
if ($this->subServices->contains($subService)) {
$this->subServices->removeElement($subService);
// set the owning side to null (unless already changed)
if ($subService->getServices() === $this) {
$subService->setServices(null);
}
}
return $this;
}
}
As you can see, in the service entity I have put #Assert\Valid() for the subservices.
Here the definition of the sub-service entity:
<?php
namespace App\Entity;
use App\Validator\SubServiceSprache;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\SubServicesRepository")
* #SubServiceSprache()
*/
class SubServices
{
/**
* #ORM\Id()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $transsubid;
/**
* #ORM\Column(type="string", length=3)
*/
private $sprache;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Services", inversedBy="subServices")
*/
private $services;
/**
* #ORM\Column(type="string", length=200)
*/
private $header;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $body;
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id)
{
$this->id = $id;
}
public function getTransSubId(): ?int
{
return $this->transsubid;
}
public function setTransSubId(int $transsubid): self
{
$this->transsubid = $transsubid;
return $this;
}
public function getsprache(): ?string
{
return $this->sprache;
}
public function setsprache(string $sprache): self
{
$this->sprache = $sprache;
return $this;
}
public function getServices(): ?Services
{
return $this->services;
}
public function setServices(?Services $services): self
{
$this->services = $services;
return $this;
}
public function getHeader(): ?string
{
return $this->header;
}
public function setHeader(string $header): self
{
$this->header = $header;
return $this;
}
public function getBody(): ?string
{
return $this->body;
}
public function setBody(?string $body): self
{
$this->body = $body;
return $this;
}
}
As you can see, for the whole class subservices I have put the validation #SubServiceSprache().
Here is the definition of the validator SubServiceSprache:
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
/**
* #Annotation
*/
class SubServiceSprache extends Constraint
{
public function validatedBy()
{
return \get_class($this).'Validator';
}
public function getTargets()
{
//PROPERTY_CONSTRAINT wenn zB. EMAIL geprüft werden soll
//CLASS_CONSTRAINT wenn ganze Entity geprüft werden soll
// jeweils das Objekt (EMAIL od. ganzes Klassenobjekt wird übergeben
return self::CLASS_CONSTRAINT;
}
}
And here the validation logic in SubServiceSpracheValidator:
<?php
namespace App\Validator;
use App\Entity\Services;
use App\Entity\SubServices;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Contracts\Translation\TranslatorInterface;
class SubServiceSpracheValidator extends ConstraintValidator
{
private $em;
private $subservice;
private $translator;
public function __construct(EntityManagerInterface $em, TranslatorInterface $translator)
{
$this->em = $em;
$this->translator = $translator;
$this->subservice = new SubServices();
}
public function validate($object, Constraint $constraint)
{
// Ist die Sprache des SubService die des Service?
if ($object instanceof SubServices) {
if($object->getServices()->getSprache() != $object->getsprache()){
// Message Translation
$message = $this->translator->trans('subservice_sprachcheck',
['subsprache' => object->getsprache(),'servsprache' => $object->getServices()->getsprache()]
);
// Assign message
$this->context->buildViolation($message)
->atPath('sprache')
->addViolation();
}
}
}
}
Here is a snippet of the form class for service:
->add('subservices', CollectionType::class,
array('entry_type' => SubservicesFormType::class,
'label' => false,
'entry_options' => array('label' => false),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'error_bubbling' => false,
))
->add('save', SubmitType::class,
array('label' => 'Sichern',
'attr' => array('class' => 'buttonsave')
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Services::class,
'error_bubbling' => false,
//'newid' => false,
]);
}
and here the one for the subservices:
class SubservicesFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sprache', LanguageType::class,
array('label' => 'Sprache',
'disabled' => false,
'attr' => array('class' => 'form-control'),
'choice_loader' => NULL,
'choices' => ['DEUTSCH' => 'de', 'ENGLISCH' => 'en'],
'choice_translation_domain' => true,
))
->add('header', TextType::class,
array('label' => 'Überschrift',
'attr' => array('class' => 'form-control')))
->add('body', TextareaType::class,
array('label' => 'Beschreibung',
'attr' => array('class' => 'form-control')))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => SubServices::class,
'validation_groups' => ['Default'],
]);
}
}
and at last my twig-file:
{% extends 'base.html.twig' %}
{% import _self as formMacros %}
{% block title %}UB Mollekopf{% endblock %}
{% block stylesheets %}
<link rel="stylesheet" href="{{ absolute_url('/css/ub_styles.css') }}" type="text/css" media="all">
<link rel="stylesheet" href="{{ absolute_url('css/font-awesome.css') }}">
{% endblock %}
{% macro printSubserviceRow(SubservicesFormType) %}
<td class="subserviceformsprache">{{ form_widget(SubservicesFormType.sprache) }}</td>
<td class="subserviceformheader">{{ form_widget(SubservicesFormType.header) }}</td>
<td class="subserviceformbody">{{ form_widget(SubservicesFormType.body) }}</td>
<td class="subserviceformaction"></td>
{% endmacro %}
{% block body %}
<div class="tableserviceedit">
{{ form_start(form) }}
<div class="tableheadereditservice">
<table id="editserviceheader">
<tr style="white-space: nowrap">
<th style="width: 100%; padding-left: 0.5em">{% trans %}Ändern Service{% endtrans %} {{ form_widget(form.id) }}</th>
</tr>
</table>
</div>
<div class="tablebodyeditservice">
<table id="editservicesingleheader">
<tr>
<th style="width: 3.5em;">{% trans %}Sprache{% endtrans %}</th>
<th style="width: 12em">{% trans %}Überschrift{% endtrans %}</th>
<th style="width: 15em">{% trans %}Beschreibung{% endtrans %}</th>
</tr>
<tr class="editserviceheader">
<td class="serviceformsprache">
{{ form_errors(form.sprache) }}
{{ form_widget(form.sprache) }}
</td>
<td class="serviceformheader">
{{ form_errors(form.header) }}
{{ form_widget(form.header) }}
</td>
<td class="serviceformbody">
{{ form_errors(form.body) }}
{{ form_widget(form.body) }}
</td>
</tr>
</table>
<div class="tablebodysubservices">
<table id="subservices">
<thead>
<tr>
<th style="width: 6em;">{% trans %}Sprache{% endtrans %}</th>
<th style="width: 22.2em">{% trans %}Überschrift{% endtrans %}</th>
<th style="width: 15em">{% trans %}Beschreibung{% endtrans %}</th>
</tr>
</thead>
<tbody id="collector" data-prototype="{{ formMacros.printSubserviceRow(form.subservices.vars.prototype)|e('html_attr') }}">
{% for subservice in form.subservices %}
<tr>
<td colspan="4">
<span style="color:red" > {{ form_errors(form) }}</span>
</td>
</tr>
<tr>
<td class="subserviceformsprache">
{{ form_widget(subservice.sprache) }}
</td>
<td class="subserviceformheader">
{{ form_widget(subservice.header) }}
</td>
<td class="subserviceformbody">
{{ form_widget(subservice.body) }}
</td>
<td class="subserviceformaction"></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="tablefooter" id="fussbereichnewservice">
<div class="btnfooter">{{ form_widget(form.save) }} <button type="" class="buttonabort">{% trans %}Abbruch{% endtrans %}</button></div>
</div>
{{ form_end(form) }}
{#</div>#}
{{ include('inc/navbar_bottom.html.twig') }}
{% endblock %}
{% block javascripts %}
<script src="{{ absolute_url('/js/main.js') }}"></script>
{% if locale == 'en' %}
<script src="{{ absolute_url('/js/subservicesen.js') }}"></script>
{% else %}
<script src="{{ absolute_url('/js/subservices.js') }}"></script>
{% endif %}
{% endblock %}
In the twig-template file I have tried serveral posibilities:
if I code {{ form_errors(form) }} the error-message will appear on every sub-service, if I code {{ form_errors(form.sprache) }} no error message will appear at all.
Does anybody have an idea to solve this?
and what happens if you try
{% for subservice in form.subservices %}
{{ form_errors(subservice ) }}
...
%}

Is there any way to have Controller, ViewModel and View without Model? It's for an Index only view

What I want to do is a parametrized report, i would love to use SSRS or other fancy tools for this but it's sort of dangerous at this point because i don't really want to mess around with the company server and I dont have much time; Also If it's a tool it should be a free and light tool and i didn't find one by now.
So, my idea is making a simple controller with Index that will return a List to View according to parameters and the View will use that ViewModel as Model then the users can export that list to CSV or PDF, the problem is: MVC is asking for a real db model to complete the scaffolding, how can this be done then?
Controller (I call an stored proc here)
public class ReporteEntregasPresentacionController : Controller
{
private EntregaMedicamentosEntities db = new EntregaMedicamentosEntities();
public ActionResult Index(DateTime DateFrom, DateTime DateTo)
{
ReporteEntregasPresentacionViewModel rep = new ReporteEntregasPresentacionViewModel();
string sqlQuery = "[dbo].[spEntregasPorPresentacion] ({0},{1})";
Object[] parameters = { DateFrom, DateTo };
rep.LstEntregasPresentacionViewModel = db.Database.SqlQuery<ItemEntregasPresentacionViewModel>(sqlQuery, parameters).ToList();
return View(rep);
}
}
ViewModel:
public class ReporteEntregasPresentacionViewModel
{
public int index;
public List<ItemEntregasPresentacionViewModel> LstEntregasPresentacionViewModel;
}
public class ItemEntregasPresentacionViewModel {
public string idProducto { get; set; }
public string Descripcion { get; set; }
public string EntregasTotales { get; set; }
}
I don't have a View now but i should be something like this:
#model EntregaMedicamentos.Models.ReporteEntregasPresentacionViewModel
<link href="~/Content/css/styles.css" rel="stylesheet" />
#{
ViewBag.Title = "ReporteEntregasPresentacion";
}
<h2>ReporteEntregasPresentacion</h2>
#using (Html.BeginForm("Index", "Entrega", FormMethod.Post))
{
<div class="card text-white bg-secondary">
<h5 class="card-header">Search</h5>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="input-group">
#Html.TextBox("DateFrom", ViewBag.currentFilter1 as DateTime?, new { #class = "form-control", placeholder = "Desde fecha", #readonly = "true", type = "datetime" })
#Html.TextBox("DateTo", ViewBag.currentFilter2 as DateTime?, new { #class = "form-control", placeholder = "Hasta fecha", #readonly = "true", type = "datetime" })
<button id="Submit4" type="submit" style='font-size:22px ;color:blue'><i class='fas fa-search'></i></button>
</div>
</div>
</div>
</div>
</div>
}
<br>
<table class="table table-striped ">
<tr class="table-primary">
<th>
Código
</th>
<th>
Producto
</th>
<th>
Entregas Totales
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.idProducto)
</td>
<td>
#Html.DisplayFor(modelItem => item.Descripcion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Valor)
</td>
</tr>
}
</table>
I ended up creating a real table/model and then it worked fine with the viewmodel. Thanks.

How can i get form->field() value?

In short, I have the following code:
<?= $form->field( $isntmodel, 'id')->textInput() ?>
<?= Html::a('<i class="mdi-action-done"></i>', ['add-item', 'id' => ???], [
'class' => 'btn-btn-add pull-right',
]) ?>
This code is wrong.
So. I need get value which will input by user. And set it instead ???
$form->field() must have $model, $attribute, $options = []. How can I write field not using $model and $attribute? It is not table column, I need just get value and set it instead ???
I try that
public function actionAddItem($id) {
$model = $this->$model;
$product = Product::findOne($id);
$orderItem = new OrderItem();
$orderItem->order_id = $model->id;
$orderItem->title = $product->title;
$orderItem->price = $product->getPrice();
$orderItem->product_id = $product->id;
$orderItem->save();
return $this->redirect(['index']);
}
But it throws an exception. At row with $model = $this->$model , and I don't know how from field submit id to link
Adding item is work if i put this in browser http://yii2-shop/backend/web/order/add-item?modelid=13&id=1&quantity=4
UPD
Now my form looks like
<?php $form = ActiveForm::begin([]); ?>
<tr>
<td><?= $n ?></td>
<td><?= $form->field( $model, 'newOrderItemId')->textInput()->label(false) ?></td>
<td></td>
<td></td>
<td class="text-center"><?= $form->field( $model, 'newOrderItemQuantity')->textInput()->label(false) ?></td>
<td>
<?= Html::a('<i class="mdi-action-done"></i>', [
'/order/add-item',
'modelid' => $model->id,
'id' => $model->newOrderItemId,
'quantity' => $model->newOrderItemQuantity,
], [
'class' => 'btn btn-add pull-right',
'data-toggle'=>'tooltip' ,
'data-placement'=>'bottom',
'title'=>'Добавить товар',
]) ?>
</td>
</tr>
<?php ActiveForm::end(); ?>
And add-item looks like
public function actionAddItem($modelid, $id, $quantity) {
$model = $this->findModel($modelid);
$product = Product::findOne($id);
$orderItem = new OrderItem();
$orderItem->order_id = $model->id;
$orderItem->title = $product->title;
$orderItem->price = $product->getPrice();
$orderItem->product_id = $product->id;
$orderItem->quantity = $quantity;
$orderItem->save();
return $this->redirect(['index']);
}
newOrderItemId and newOrderItemQuantity are just public variables which I mark at Order model. I can't get form field value for submit it to add-item
So. I solved the problem.
I created AddOrderItem model for announce variables
<?php namespace backend\models;
use yii\base\Model;
class AddOrderItem extends Model {
public $modelid;
public $id;
public $quantity;
public function rules() {
return [
[['modelid','id','quantity'], 'integer'],
];
}
}
And I edited actionUpdate() now it's looks like
public function actionUpdate($id) {
$model = $this->findModel($id);
$addOrderModel = new AddOrderItem();
if ($addOrderModel->load(Yii::$app->request->post())) {
$product = Product::findOne($addOrderModel->id);
$orderItem = new OrderItem();
$orderItem->order_id = $model->id;
$orderItem->title = $product->title;
$orderItem->price = $product->getPrice();
$orderItem->product_id = $product->id;
$orderItem->quantity = $addOrderModel->quantity;
$orderItem->save();
return $this->redirect(['view', 'id' => $model->id]);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
'addOrderModel' => $addOrderModel
]);
}
}
At views/order/update i added following row
<?= $this->render('_addItemForm', ['model' => $addOrderModel]); ?>
And _addItemForm now contains this:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(); ?>
<td><?= $form->field( $model , 'id')->textInput()->label(false) ?></td>
<td></td>
<td></td>
<td class="text-center"><?= $form->field( $model , 'quantity')->textInput()->label(false) ?></td>
<td>
<?= Html::submitButton('<i class="mdi-action-done"></i>',[
'class' => 'btn btn-add pull-right',
'data-toggle'=>'tooltip' ,
'data-placement'=>'bottom',
'title'=>'Добавить товар',
]) ?>
</td>
<?php ActiveForm::end(); ?>
I can't believe what I done it by myself. And I'm glad that I had no one to help, because now I know more.

Access an id of a user in a table from a controller

PHP, Zend Framework, Apache, MySql.
I want to edit a user in a list by clicking its corresponding edit button.
when i click the edit button, the corresponding users id should be send to the controller from where it should be accessed.
But I cant seem to get the user id in the controller.
After getting the id , i want to populate the fields in edit.phtml with the data retrieved view model.
Since i cant access the id, i cant populate the fields.
The url is like /Sample/user/edit/2 where 2 is id of a user.
UserController.php
<?php
class UserController extends Zend_Controller_Action
{
protected $_user;
public function init()
{
/* Initialize action controller here */
$this->_user = new Application_Model_User();
}
public function indexAction()
{
// action body
}
public function listAllAction()
{
// action body
$this->view->users = $this->_user->listUsers();
}
public function registerAction()
{
// action body
if($this->getRequest()->isPost())
{
$data = array(
'user_uname' => $this->_request->getParam('uname'),
'user_pwd' => $this->_request->getParam('paswd'),
'user_address' => $this->_request->getParam('address')
);
$this->_user->insert($data);
}
}
public function editAction()
{
// action body
**$u_id = $this->_request->getParam('user_id');**
// print_R("Hi ".$u_id);
// exit;
if($this->_request->isPost())
{
$u_id = $this->_request->getPost('user_id');
//print_R("Hi ".$u_id);
//exit;
}
else
{
**$this->view->user = $this->_user->getUser($u_id);**
}
}
}
Model class
<?php
class Application_Model_User extends Zend_Db_Table_Abstract
{
protected $_name="tbl_user";
public function listUsers()
{
// action body
$sql = "select * from tbl_user";
$result = $this->_db->query($sql);
return $result->fetchAll();
}
public function getUser($id)
{
$query = "select * from tbl_user where user_id = ?";
return $this->_db->fetchRow($query,array($id));
}
}
ListUser.phtml
<html>
<head></head>
<body>
<b><center>List of Users</center></b>
<form name="list_users" method="post" action="">
<table>
<tr><th>ID</th>
<th>Name</th>
<th>Password</th>
<th>Address</th>
<th>Action</th>
</tr>
<?php foreach ($this->users as $usr): ?>
<tr>
<td><?php echo $usr['user_id'] ?></td>
<td><?php echo $usr['user_uname'] ?></td>
<td><?php echo $usr['user_pwd'] ?></td>
<td><?php echo $usr['user_address'] ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan=2>Add More Users</td>
</tr>
</table>
</form>
</body>
</html>
edit.phtml
<html>
<head></head>
<body>
<form name="user_edit" method="post" action="<?php print $this->baseUrl(); ?>/user/edit">
<b><center>Edit Profile</center></b>
<table>
<tr>
<td>Username</td>
<td><input type="text" name="uname" id="uname1" value="<?php print $this->user['user_uname'] ?>"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="paswd" id="paswd1"/></td>
</tr>
<tr>
<td>Address</td>
<td><textarea type="text" name="address" id="address1"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='edit_user' value='Update User'/></td>
</tr>
<tr>
<td colspan=2>See All Users</td>
</tr>
</table>
</body>
</html>
Thank you in advance..
I got the answer.
In usercontroller's editaction change the code $u_id = $this->_request->getParam('user_id'); to $u_id = $this->getRequest()->getParam('id');
Small change needed: change the following line:
<td>Edit</td>
to
<td>Edit</td>

what is the difference between form and chtml in yii

confusion between form and chtml
i used to form to write form ans submit to database working fine, but for some particular places, according to google search used CHTML instead of form. but when i submitted that form to database
CHTML textfield value is not submitting to database
here goes my code
_Form.php
<script language="javascript">
function firstlang(flang,slang,tlang,math,scien,soci)
{
var sflang=parseInt(flang)+parseInt(slang)+parseInt(tlang)+parseInt(math)+parseInt(scien)+parseInt(soci);
document.getElementById('totalmarks').value=sflang;
if(sflang>=300 && sflang<400)
{
var flang='C';
document.getElementById('grade').value=flang;
}
else if(sflang>=400 && sflang<500)
{
var flang='B';
document.getElementById('grade').value=flang;
}
else if(sflang>=550 && sflang<=600)
{
var flang='A';
document.getElementById('grade').value=flang;
}
}
</script>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'marks-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'focus'=>array($model,'class'),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<table width="200" border="1">
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'class'); ?></span></td>
<td><span class="row">
<?php echo CHtml::dropDownList('class','',CHtml::listData(class1::model()->findAll(),'class','class'),array('empty'=>'Choose one',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('Marks/dynamicstates'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#studentid', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
//empty since it will be filled by the other dropdown
?></span></td>
<td><span class="row"><?php echo $form->error($model,'class'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'studentid'); ?></span></td>
<td><span class="row"><?php echo CHtml::dropdownlist('studentid','',array()); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'studentid'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'examtype'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'examtype',array('size'=>30,'maxlength'=>30)); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'examtype'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'firsttlanguage'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'firsttlanguage',array('id'=>'firsttlanguage','value'=>'0','onkeyup'=>'firstlang(this.value,secondlanguage.value,thirdlanguage.value,mathematics.value,science.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'firsttlanguage'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'secondlanguage'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'secondlanguage',array('id'=>'secondlanguage','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,thirdlanguage.value,mathematics.value,science.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'secondlanguage'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'thirdlanguage'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'thirdlanguage',array('id'=>'thirdlanguage','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,secondlanguage.value,mathematics.value,science.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'thirdlanguage'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'mathematics'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'mathematics',array('id'=>'mathematics','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,secondlanguage.value,thirdlanguage.value,science.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'mathematics'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'science'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'science',array('id'=>'science','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,secondlanguage.value,thirdlanguage.value,mathematics.value,social.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'science'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'social'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'social',array('id'=>'social','value'=>'0','onkeyup'=>'firstlang(this.value,firsttlanguage.value,secondlanguage.value,thirdlanguage.value,mathematics.value,science.value)')); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'social'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'totalmarks'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'totalmarks',array('id'=>'totalmarks','size'=>5,'maxlength'=>5)); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'totalmarks'); ?></span></td>
</tr>
<tr>
<td><span class="row"><?php echo $form->labelEx($model,'grade'); ?></span></td>
<td><span class="row"><?php echo $form->textField($model,'grade',array('id'=>'grade','size'=>5,'maxlength'=>5)); ?></span></td>
<td><span class="row"><?php echo $form->error($model,'grade'); ?></span></td>
</tr>
<tr>
<td> </td>
<td><span class="row buttons"><?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?></span></td>
<td> </td>
</tr>
</table>
<?php $this->endWidget(); ?>
</div><!-- form -->
MarksController.php
<?php
class MarksController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','dynamicstates'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Marks;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Marks']))
{
$model->attributes=$_POST['Marks'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Marks']))
{
$model->attributes=$_POST['Marks'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Marks');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Marks('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Marks']))
$model->attributes=$_GET['Marks'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Marks::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='marks-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actiondynamicstates()
{
// $model1=new Examresults;
/*$exam_type=(int)$_POST['exam_type'];
if ($exam_type==0)
$data=array(0=>'States:');
else if ($exam_type==1)
$data=array(1=>'Alaska', 2=>'California');
else if ($exam_type==2)
$data=array(1=>'Orleans', 2=>'Bordeaux');
else if ($exam_type==3)
$data=array(1=>'Hokkaido', 2=>'Okinawa');*/
//$schoolfee = feesettings::model()->find("feetype='schoolfee' and class='".$_REQUEST['class']."'");
$data=admission::model()->findAll('class=:class',
array(':class'=>$_POST['class']));
$data=CHtml::listData($data,'studentid','studentfname');
foreach($data as $value=>$name)
echo CHtml::tag('option', array('value'=>$value), CHtml::encode($name), true);
}
}
Marks.php
<?php
/**
* This is the model class for table "marks".
*
* The followings are the available columns in table 'marks':
* #property integer $id
* #property string $class
* #property string $studentid
* #property string $examtype
* #property integer $firsttlanguage
* #property integer $secondlanguage
* #property integer $thirdlanguage
* #property integer $mathematics
* #property integer $science
* #property integer $social
* #property integer $totalmarks
* #property string $grade
*/
class Marks extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Marks the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'marks';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('class, studentid', 'required'),
array('firsttlanguage, secondlanguage, thirdlanguage, mathematics, science, social, totalmarks', 'numerical', 'integerOnly'=>true),
array('class, studentid, examtype', 'length', 'max'=>30),
array('grade', 'length', 'max'=>5),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, class, studentid, examtype, firsttlanguage, secondlanguage, thirdlanguage, mathematics, science, social, totalmarks, grade', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'class' => 'Class',
'studentid' => 'Studentid',
'examtype' => 'Examtype',
'firsttlanguage' => 'Firsttlanguage',
'secondlanguage' => 'Secondlanguage',
'thirdlanguage' => 'Thirdlanguage',
'mathematics' => 'Mathematics',
'science' => 'Science',
'social' => 'Social',
'totalmarks' => 'Totalmarks',
'grade' => 'Grade',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('class',$this->class,true);
$criteria->compare('studentid',$this->studentid,true);
$criteria->compare('examtype',$this->examtype,true);
$criteria->compare('firsttlanguage',$this->firsttlanguage);
$criteria->compare('secondlanguage',$this->secondlanguage);
$criteria->compare('thirdlanguage',$this->thirdlanguage);
$criteria->compare('mathematics',$this->mathematics);
$criteria->compare('science',$this->science);
$criteria->compare('social',$this->social);
$criteria->compare('totalmarks',$this->totalmarks);
$criteria->compare('grade',$this->grade,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
Have a look here Creating Form. Since Yii 1.1.1 there is a widget called CActiveForm
so when you use this widget you create the form inputs with $form->textField($model,'username')instead of using CHtml::activeTextField($model,'username')but both work in the same way.
So if that field is not being saved in the database it's probably because you haven't added it to the rules of your model.
public function rules() {
return array(
array('username', 'safe'),
);
)