what is the difference between form and chtml in yii - forms

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'),
);
)

Related

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

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>

Symfony 3.2 CollectionType

Here's my problem. In my project, I have a one-to-many relationship between class FactureAchat and LigneFactureAchat, when I add a Facture the products are added in the Table ligne_facture_achat without having adding the foreign key of my Facture and an error is produced "Could not determine access type for property "LinesInvoicesPurchases". " the same problem with the display of a facture with its products. "An exception has been thrown during the rendering of a template (" Notice: Undefined index: factureachat ")."
FactureAchat Entity
/*----- added from facture---*/
/**
* #ORM\OneToMany(targetEntity="LigneFactureAchat", mappedBy="factureachat",cascade={"all"})
* #Assert\Valid()
*/
protected $lignesFacturesAchats;
public function __construct() {
$this->lignesFacturesAchats = new ArrayCollection();
$this->dateCreation = new \DateTime();
$this->dateEcheance = new \DateTime();
}
/**
* Get lignesFacturesAchats
*
* #return \AppBundle\Entity\LigneFactureAchat
*/
public function getLignesFacturesAchats() {
return $this->lignesFacturesAchats;
}
public function addLignesFactureAchat(LigneFactureAchat $l) {
$l->setFactureAchat($this);
$this->lignesFacturesAchats->add($l);
}
public function removeLignesFactureAchat(LigneFactureAchat $l) {
$this->lignesFacturesAchats->removeElement($l);
}
LigneFactureAchat Entity
/**
* #var \FactureAchat
*
* #ORM\ManyToOne(targetEntity="FactureAchat",inversedBy="lignesFacturesAchats",cascade={"persist"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="facture_achat_id", referencedColumnName="id")
* })
*/
private $factureAchat;
/**
* Set factureAchat.
*
* #param \AppBundle\Entity\FactureAchat|null $factureAchat
*
* #return LigneFactureAchat
*/
public function setFactureAchat(\AppBundle\Entity\FactureAchat $factureAchat = null)
{
$this->factureAchat = $factureAchat;
return $this;
}
/**
* Get factureAchat.
*
* #return \AppBundle\Entity\FactureAchat|null
*/
public function getFactureAchat()
{
return $this->factureAchat;
}
FactureAchat Form
$builder->add('lignesFacturesAchats', CollectionType::class, array(
'entry_type' => LigneFactureAchatType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'mapped' => true,
'by_reference' => false
));
FactureAchatController
/**
* Creates a new factureachat entity.
*
* #Route("/new", name="factureachat_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$retenus = $em->getRepository('AppBundle:Retenu')->findAll();
$factureachat = new FactureAchat();
$form = $this->createForm('AppBundle\Form\FactureAchatType', $factureachat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($factureachat);
$em->flush($factureachat);
// var_dump($factureachat->getLignesFacturesAchats());die;
if ($form->get('saveAndPrint')->isClicked()) {
return $this->redirectToRoute('factureachat_print', array('id' => $factureachat->getId()));
}
// return $this->redirectToRoute('factureachat_show', array('id' => $factureachat->getId()));
}
return $this->render('factureachat/new.html.twig', array(
'factureachat' => $factureachat,
'form' => $form->createView(),
'retenus' => $retenus
));
}
/**
* #Route("/{id}/show",name="factureachat_show")
* #Method({"GET","POST"})
*/
public function showAction(Request $request, FactureAchat $factureachat) {
$form_regler = $this->createFormBuilder($factureachat)
->add('termine', \Symfony\Component\Form\Extension\Core\Type\HiddenType::class, array(
'data' => true
))
->add('terminerAndRegler', \Symfony\Component\Form\Extension\Core\Type\SubmitType::class, array('label' => 'Terminer la facture et régler', 'attr' => ['class' => 'btn-success']))
->getForm();
$form_imprimer = $this->createFormBuilder($factureachat)
->add('termine', \Symfony\Component\Form\Extension\Core\Type\HiddenType::class, array(
'data' => true
))
->add('terminerAndImprimer', \Symfony\Component\Form\Extension\Core\Type\SubmitType::class, array('label' => 'Terminer la facture et imprimer', 'attr' => ['class' => 'btn-success']))
->getForm();
$form_regler->handleRequest($request);
$form_imprimer->handleRequest($request);
if ($form_regler->isSubmitted() && $form_regler->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirectToRoute('factureachat_reglements', array('id' => $factureachat->getId()));
}
if ($form_imprimer->isSubmitted() && $form_imprimer->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirectToRoute('factureachat_print', array('id' => $factureachat->getId()));
}
return $this->render('factureachat/show.html.twig', array(
'factureachat' => $factureachat,
'form_regler' => $form_regler->createView(),
'form_imprimer' => $form_imprimer->createView(),
'lignesFacturesAchats' => $factureachat->getLignesFacturesAchats()
));
}
show.html.twig View
<div id="collapseTwo" class="panel-collapse collapse in">
<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Réf</th>
<th>Désignation</th>
<th>Unité</th>
<th>PU HT</th>
<th>Remise</th>
<th>TVA</th>
<th>PU TTC</th>
<th>Qte</th>
<th>Total TTC</th>
</tr>
</thead>
<tbody>
{% set i=0 %}
{% for ligne in factureachat.lignesFacturesAchats %}
<tr class="item">
<td class="left">{{ligne.article.code}}</td>
<td class="left">{{ligne.designation}}</td>
<td class="left">{{ligne.article.unite}}</td>
<td class="center" id="prixUnitaire_{{i}}">{{ligne.prixUnitaire}}</td>
<td class="center" id="remise_{{i}}">{{ligne.remise}} %</td>
<td class="center" id="tva_{{i}}">{{ligne.tva }} %</td>
{% set puTTC=ligne.ttc/ligne.qte %}
<td class="center" id="ttc_{{i}}">{{ puTTC|number_format(3, '.', '') }}</td>
<td class="center" id="qte_{{i}}">{{ligne.qte}}</td>
<td class="center" id="total_{{i}}">{{ligne.ttc }}</td>
</tr>
{% set i=i+1 %}
{% endfor %}
<div id="lignesFacturesLength" style="visibility: hidden">{{i}}</div>
</tbody>
</table>
</div>
</div>
</div>
the error "An exception has been thrown during the rendering of a template (" Notice: Undefined index: factureachat ")." occurred on line
{% for ligne in factureachat.lignesFacturesAchats %}
Any help please

Magento 2 get order in custom block

I have a custom module which sends email to custom email address after successful purchase. It works well but now I need to get gift message from order.
Here is my Block code
<?php
namespace Test\Test2\Block\Vendor\Shipment;
class Items extends \Magento\Framework\View\Element\Template
{
const DEFAULT_TYPE = 'default';
public function getItemRenderer($type)
{
/** #var \Magento\Framework\View\Element\RendererList $rendererList */
$rendererList = $this->getRendererListName() ? $this->getLayout()->getBlock($this->getRendererListName()) : $this->getChildBlock('renderer.list');
if (!$rendererList) {
throw new \RuntimeException('Renderer list for block "' . $this->getNameInLayout() . '" is not defined');
}
$overriddenTemplates = $this->getOverriddenTemplates() ?: [];
$template = isset($overriddenTemplates[$type]) ? $overriddenTemplates[$type] : $this->getRendererTemplate();
$renderer = $rendererList->getRenderer($type, self::DEFAULT_TYPE, $template);
$renderer->setRenderedBlock($this);
return $renderer;
}
public function getItemHtml(\Magento\Framework\DataObject $item)
{
$block = $this->getItemRenderer($item->getProductType())->setItem($item);
return $block->toHtml();
}
}
and email template .phtml
<?php $_items = $block->getItems() ?>
<?php $_order = $block->getOrder() ?>
<?php if ($_items): ?>
<table class="items email-items shipment-items order-items">
<thead>
<tr>
<th class="item-info">
<?= /* #escapeNotVerified */ __('Items'); ?>
</th>
<th class="item-price">
<?= /* #escapeNotVerified */ __('Price'); ?>
</th>
<th class="item-qty">
<?= /* #escapeNotVerified */ __('Qty'); ?>
</th>
<th class="row-total">
<?= /* #escapeNotVerified */ __('Total'); ?>
</th>
</tr>
</thead>
<?php foreach ($_items as $_item): ?>
<?php
if ($_item->getParentItem()) {
continue;
}
?>
<tbody>
<?= $block->getItemHtml($_item) ?>
</tbody>
<?php endforeach; ?>
</table>
<?php $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_order->getGiftMessageId()); ?>
<?php if ($_giftMessage): ?>
<br />
<table class="message-gift">
<tr>
<td>
<h3><?= /* #escapeNotVerified */ __('Gift Message for this Order') ?></h3>
<strong><?= /* #escapeNotVerified */ __('From:') ?></strong> <?= $block->escapeHtml($_giftMessage->getSender()) ?>
<br /><strong><?= /* #escapeNotVerified */ __('To:') ?></strong> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?>
<br /><strong><?= /* #escapeNotVerified */ __('Message:') ?></strong>
<br /><?= $block->escapeHtml($_giftMessage->getMessage()) ?>
</td>
</tr>
</table>
<?php endif; ?>
<?php endif; ?>
Obviously, I receive this error message:
Uncaught Error: Call to a member function getGiftMessageId()
since my block does not have the method getOrder.
But if I try to copy getOrder method from Magento\Sales\Block\Order\Items:
/**
* Retrieve current order model instance
*
* #return \Magento\Sales\Model\Order
*/
public function getOrder()
{
return $this->_coreRegistry->registry('current_order');
}
with __construct part
/**
* #param \Magento\Framework\View\Element\Template\Context $context
* #param \Magento\Framework\Registry $registry
* #param array $data
* #param \Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory|null $itemCollectionFactory
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = [],
\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory $itemCollectionFactory = null
) {
$this->_coreRegistry = $registry;
$this->itemCollectionFactory = $itemCollectionFactory ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory::class);
parent::__construct($context, $data);
}
it still shows an error that order object in null. What am I doing wrong? Or how can I obtain order object in my case? Thanks.

Disable or change validation for embedded form fields in Symfony1 form

I am trying to cancel validation in embedded forms based on a value from main form.
By default, embedded forms fields have validator option set to 'required'=>true. So it gets validated like that. If user leave any field blank, the form does not pass validation and blank fields get marked in template (different style).
What I am trying to do is to change option:"required" to false for all fields in embedded form.
I tried to do that in post validator callback method, but it seems that it is not possible that way.
The main form code:
class TestForma extends sfForm
{
public function configure()
{
$this->setWidgets(array(
'validate_items' => new sfWidgetFormChoice(array(
'choices' => array('no' => 'No', 'yes' => 'Yes'),
'multiple' => false,'expanded'=>true,'default' => 'no')),
));
$this->setValidators(array('validate_items' => new sfValidatorPass()));
$this->widgetSchema->setNameFormat('testforma[%s]');
$subForm = new sfForm();
for ($i = 0; $i < 2; $i++)
{
$form = new ItemForma();
$subForm->embedForm($i, $form);
}
$this->embedForm('items', $subForm);
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'postValidate')))
);
}
Post-validator code:
public function postValidate($validator,$values)
{
$validatorSchema = $this->getValidatorSchema();
if($values['validate_items']=='no')
{
$itemsValidatorSchema = $validatorSchema['items'];
$itemsFieldsValidatorSchemes = $itemsValidatorSchema->getFields();
foreach($itemsFieldsValidatorSchemes as $itemValidatorScheme)
{
$itemValidatorScheme['color']->setOption('required',false);
$itemValidatorScheme['shape']->setOption('required',false);
}
}
return $values;
}
Embedded form class:
class ItemForma extends sfForm
{
public function configure()
{
$this->setWidgets(array(
'color' => new sfWidgetFormInputText(),
'shape' => new sfWidgetFormInput(),
));
$this->setValidators(array(
'color' => new sfValidatorString(array('required'=>true)),
'shape' => new sfValidatorEmail(array('required'=>true)),
));
$this->widgetSchema->setNameFormat('items[%s]');
}
}
Template code:
<form action="<?php echo url_for('weather/formiranje')?>" method="post">
<?php
foreach($form->getErrorSchema()->getErrors() as $e)
{
echo $e->__toString();
}
?>
<table>
<tfoot>
<tr>
<td colspan="2">
<input type="submit" value="OK" />
</td>
</tr>
</tfoot>
<tbody>
<tr><th>Main form</th></tr>
<tr><td><?php echo $form['validate_items']->renderLabel() ?>
<span class="<?php echo $form['validate_items']->hasError() ? 'rowError' : ''?>">
<?php echo $form['validate_items'] ?></span>
</td></tr>
<tr><td> </td></tr>
<tr><th>Embedded forms</th></tr>
<?php
foreach($form['items'] as $item)
{
?>
<tr>
<td><span class="<?php echo $item['color']->hasError() ? 'rowError' : ''?>">
<?php echo $item['color']->renderLabel() ?>
<?php echo $item['color'] ?></span>
</td>
</tr>
<tr>
<td><span class="<?php echo $item['shape']->hasError() ? 'rowError' : ''?>">
<?php echo $item['shape']->renderLabel() ?>
<?php echo $item['shape'] ?></span>
</td></tr>
<?php
}
echo $form['_csrf_token'];
?>
</tbody>
</table>
</form>
The way you organised it won't work because the post validator is run after all the field validators, so they've already been checked and marked as failed. (because the fields were required).
You could try the same approach you have here but with setting a preValidator instead of a postValidator. I think it should work then.
If it still won't work as expected what I would do is to change the default settings on the embedded form's fields to 'required' = false and use the postValidator. In the validator you could check whether or not you need to validate the embedded fields. If you need to validate them you can check if their values are set and if not you can throw errors for those fields. (I hope this is explained clearly)
Another thing you could try is to re-run the validation for the chosen fields. So something like that in your postValidator:
$itemValidatorScheme['color']->setOption('required',false);
$itemValidatorScheme['color']->clean($values['name_of_the_field']);

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>