I am using a Yii hiddenField in a CActiveForm widget. I have saved this hidden field value in database. There is no issue with storing in DB with Controller action at all. after saving this the hidden field should display the value. And how can I populate the form with the database stored value. Or how to refer some other field in the form to contain value from DB after save is processed.
<?php echo $form->hiddenField($model,'ad_form_id',array('value'=>$base)); ?>
My controller action
public function actionBCFormFields()
{
$model=new BCFormField();
if(isset($_POST['BCFormField']))
{
$model->ad_form_id = $_POST['BCFormField']['ad_form_id'];
$model->attributes=$_POST['BCFormField'];
if ($model->save()){
echo'saved';
}
$this->redirect(array('create',
'crm_base_form_field_id'=>$model->crm_base_form_field_id));
}
Based on the very litle code you have given us i would suggest something like this in your controller, but if you edit your question and elaborate , i will edit my question:
public $ad_form_id
public function actionCreate()
{
$model = new User;
$this->ad_form_id = $this->base;
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
$this->base = $this->ad_form_id;
if ($model->validate() && $model->save()) {
$this->redirect(array('view'));
}
}
$this->render('create',array('model' => $model,));
}
Related
I've Yii2 form containing form fields depending on action of page. Ex. Few fields appears when then action is create and few appears when action is update. I want to add required validation based on this scenario.
Ex.
<?= $form->field($model, 'unique_identifier')->textInput(['maxlength' => 45]) ?>
I am showing this field only when action => 'update'.
Now I want to add required validation for this and I tried this:
[['unique_identifier'], 'required', 'on' => 'update'],
But above validation not working. If I remove on=>update then its validating on both create and update scenario.
Any help would be appreciated.
ActiveRecord does not set scenario automaticaly when you update or create items. You must override update() method in your model and set scenario that you need. E.g. in your case
public function update($runValidation = true, $attributeNames = null)
{
$this->scenario = 'update';
return parent::update($runValidation, $attributeNames);
}
Also you can set scenario in your actionUpdate
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
//load data from request, save model etc.
}
In my app, Comment model is rendered partially in Product view.
Everything is alright except that after I added a new column to my comment table, I cannot save data into the new column (named 'ddate').
Even I tried this:
$_POST['Comment']['ddate'] = 'something';
$model2->attributes=$_POST['Comment'];
$model2->save();
but not working!
$temp = $model->attributes;
$model->setFields($_POST['Comment'];);
$model->ddate = $_POST['Comment']['ddate'];
if($model->save())
{
echo "saved";
}
You have to set the attribute as 'safe' in the model, or the form value won't be copied to the model when $model2->attributes = $_POST['Comment']; is called.
Example:
public function rules() {
return array(
array('ddate', 'safe'),
);
}
If you always want ddate to be the current date/time, it might be better to set it in beforeSave() instead:
protected function beforeSave() {
if($this->hasAttribute('ddate') && !isset($this->ddate))
$this->ddate = date("Y-m-d H:i:s");
I have came across with one problem i need to show different form elements
Based on different condition to the user i know it will be easy in core php but want to do in zend environment
EXAMPLE:
If person is disabled we will show two radio buttons
$disable = new Shaadi_Form_Element_radio('disablitiy');
$disableArr = array(""=>" Doesn't Matter","Y"=>" show disabled");
IF he is not disabled
$disable = new Shaadi_Form_Element_radio('disablitiy');
$disableArr = array(""=>" Doesn't Matter","N"=>" do not show disabled");
I want this code to be done in form how can I optimize this please help me
Whenever a form - or any object, for that matter - is dependent upon some information external to the form, I usually pass that information in the form's constructor. Then I inspect it later in init() when I am building the form.
Example:
class My_Form extends Zend_Form
{
protected $hasDisability;
public function __construct($hasDisability)
{
$this->hasDisability = (bool) $hasDisability;
parent::__construct();
}
public function init()
{
// Add all your other elements
// Blah, blah
// Add the element that is dependent upon the $hasDisability value
$disable = new Shaadi_Form_Element_radio('disablitiy');
$disableArr = $this->hasDisability
? array(""=>" Doesn't Matter","Y"=>" show disabled")
: array(""=>" Doesn't Matter","N"=>" do not show disabled");
// Add the $disableArr into the radio element
$disable->setMultiOptions($disableArr);
}
}
Usage - perhaps in a controller - is then something like:
$form = new My_Form(true); // for a disabled used
$form = new My_Form(false); // for a non-disabled user
To implement the element in form, based on some condition, you need to pass the user disability option in form constructor through controller.
You can perform below steps to display radio button in view:
Form code:
class Application_Form_User extends Zend_Form {
public function init() {
$formAttribs = $this->getAttribs();
$isDisable = $formAttribs['disable'];
if (!$disabled) {
$disableArr = array(""=>" Doesn't Matter","Y"=>" show disabled");
} else {
$disableArr = array(""=>" Doesn't Matter","N"=>" do not show disabled");
}
$this->addElement('radio', 'disability', array(
'label' => 'Disability',
'required' => true,
'multiOptions' => $disableArr,
));
}
}
In controller:
public function addAction() {
$disable = ($user->disable) ? true : false;
$form = new Application_Form_User(array('disable' => $disable));
$this->view->form = $form;
}
In view you can get 'disability' element as below :
<?php echo $this->form->getelement('disability'); ?>
In your form, define your radio element:
$disable = new Shaadi_Form_Element_radio('disablitiy');
In your Controller, call this element and add the good options:
if ($disable)
$disableArr = array(""=>" Doesn't Matter","Y"=>" show disabled");
else
$disableArr = array(""=>" Doesn't Matter","N"=>" do not show disabled");
$form->getElement('disablitiy')->setMultiOptions($disableArr);
I have the following code for updating a Yii model:
public function actionSettings($id) {
if (!isset($_POST['save_hostname']) && isset($_POST['Camera']) && isset($_POST['Camera']['hostname'])) {
$_POST['Camera']['hostname'] = '';
}
$model = $this->loadModel($id);
$model->setScenario('frontend');
$this->performAjaxValidation($model);
if (isset($_POST['Camera'])) {
$model->attributes = $_POST['Camera'];
unset($model->api_password);
if ($model->save()) {
Yii::app()->user->setFlash('success', "Camera settings has been saved!");
} else {
Yii::app()->user->setFlash('error', "Unable to save camera settings!");
}
}
$this->render('settings', array(
'model' => $model,
));
}
This works fine, except in my model I have code like this:
<h1>Settings For: <?php echo CHtml::encode($model->name); ?></h1>
The problem is that, even when the user input fails validation, the h1 tag is having bad input echoed out into it. If the input fails the validation, the h1 attribute should stay the same.
I can 'reset' the $model variable to what is in the database before the view is returned, but this then means I don't get any error feedback / validation failed messages.
Is my only option to have 2 $models ($model and $data perhaps), one used for handling the form and the other for sending data to the page? Or does someone have a more elegant solution?
performAjaxValidation assigns all save attributes to the model so this behavior is normal.
I would reload model if save fails.
$model->refresh();
I have a form with some text fields and I have a preview button that needs to submit the form to the same controller. And then in the controller, I need to extract the values and populate a form with these values for the template to see. What is the best way to achieve this? I'm a newbe so please be clear.
Sample controller:
public function myControllerName(sfWebRequest $request)
{
$this->form = new myFormClass();
}
Use <?php echo $form->renderFormTag( url_for('#yourRoutingName'), array('method' => 'POST') ); ?> in your template and change #yourRoutingName to the one pointing to your controller.
Now change your controller to be something like this:
public function myControllerName(sfWebRequest $request)
{
$this->form = new myFormClass();
if ($request->isMethod(sfRequest::POST)
{
$this->form->bind( $request->getParameter( $this->form->getName() ) );
// Check if the form is valid.
if ($this->form->isValid())
{
$this->form->save();
// More logic here.
}
}
}
The $this->form->bind( $request->getParameter( $this->form->getName() ) ); part binds posted data to your form where $this->form->isValid() returns a boolean whether the form is valid or not.
Have you tried this ?
$this->redirect($request->getReferer()); //action
if not, then please try and check if its work for you.
Thanks.