I am trying to upload files from a form and then save it in a directory uvis_front_user_files which is located under web/uploads but when i save the form everything goes well but the files are not there in the destination directory.
Even the file name is saved in database but in the uvis_front_user_files directory there is nothing.
Form:
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="heading heading-tertiary heading-border text-center">
<h4 class="heading-tertiary"><?php echo $quiz['title'] ?></h4>
<p><?php echo $quiz['description'] ?></p>
</div>
<?php if ($sf_user->hasFlash('success')): ?>
<div class="alert alert-success">
<?php echo $sf_user->getFlash('success'); ?>
</div>
<?php endif; ?>
<div class="col-md-6 col-md-offset-3">
<form method="POST" action="" enctype="multipart/form-data">
<?php echo $form->renderGlobalErrors(); ?>
<table class="sample-order-frm" width="100%">
<?php echo $form['name']->renderRow() ?>
<?php echo $form['email']->renderRow() ?>
</tr>
</table>
<?php $current = current($quiz['questions']) ?>
<?php if ($current["text"] !== NULL): ?>
<h4 class="heading-tertiary">Please leave blank the questions that do not apply:</h4>
<ol class="survey-ques-list">
<?php foreach ($quiz['questions'] as $questionId => $question): ?>
<li>
<label><?php echo $question['text']; ?></label>
<?php echo $form['question_'.$questionId]->render(); ?>
<?php echo $form['path']->render(); ?>
<?php echo $form['question_'.$questionId]->renderError(); ?>
</li>
<?php endforeach; ?>
</ol>
<br />
<?php endif; ?>
<?php echo $form->renderHiddenFields(false); ?>
<div class="text-center">
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-tertiary btn-lg"/>
</div>
</form>
</div>
</div>
</div>
</div>
Action File:
<?php
/**
* uvisQuiz actions.
*
* #package we.com
* #subpackage uvisQuiz
* #version SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
*/
class uvisQuizActions extends sfActions {
/**
* Executes index action
*
* #param sfRequest $request A request object
*/
public function executeIndex(sfWebRequest $request) {
$this->forward404Unless($slug = $request->getParameter('slug'));
$this->forward404Unless($this->quiz = UvisQuizFrontPeer::getQuizBySlug($slug));
$this->form = new UvisQuizCustomForm(null, array('questions' => $this->quiz['questions']));
if($request->isMethod('POST')){
$params = $request->getParameter($this->form->getName());
$this->form->bind($params, $request->getFiles($this->form->getName()));
//$this->form->bind($params);
if($this->form->isValid()){
$uvisQuizUserObj = UvisQuizFrontPeer::saveQuiz($this->quiz, $params);
$this->getUser()->setFlash('completed_video_survey', true);
$this->redirect('#uvis_quiz_complete?slug='.$request->getParameter('slug'));
}
}
}
public function executeComplete(sfWebRequest $request) {
$this->forward404Unless($slug = $request->getParameter('slug'));
$this->forward404Unless($this->singleQuiz = UvisQuizFrontPeer::getQuizBySlug($slug));
$this->forward404Unless($this->getUser()->hasFlash('completed_video_survey'));
}
}
UvisQuizFrontPeer:
<?php
class UvisQuizFrontPeer extends BaseUvisQuizPeer {
public static function getQuizBySlug($slug) {
$criteria = new Criteria();
$criteria->addSelectColumn('uvis_quiz.id as id');
$criteria->addSelectColumn('uvis_quiz.title as title');
$criteria->addSelectColumn('uvis_quiz.description as description');
$criteria->addSelectColumn('uvis_quiz.path as path');
$criteria->addSelectColumn('uvis_quiz_question.id as question_id');
$criteria->addSelectColumn('uvis_quiz_question.question as question_text');
$criteria->addSelectColumn('uvis_quiz_question.answer_type as answer_type');
$criteria->addSelectColumn('uvis_quiz_question_answer.id as answer_id');
$criteria->addSelectColumn('uvis_quiz_question_answer.answer as answer_text');
$criteria->addJoin(self::ID, UvisQuizQuestionPeer::QUIZ_ID, Criteria::LEFT_JOIN);
$criteria->addJoin(UvisQuizQuestionPeer::ID, UvisQuizQuestionAnswerPeer::QUIZ_QUESTION_ID, Criteria::LEFT_JOIN);
$criteria->add(self::SLUG, $slug);
$criteria->add(self::DELETED_AT, null, Criteria::ISNULL);
$criteria->add(UvisQuizQuestionPeer::DELETED_AT, null, Criteria::ISNULL);
$criteria->add(UvisQuizQuestionAnswerPeer::DELETED_AT, null, Criteria::ISNULL);
$records = self::doSelectStmt($criteria)->fetchAll(PDO::FETCH_ASSOC);
$quizData = array();
foreach ($records as $record) {
if (!isset($quizData['id'])) {
$quizData['id'] = $record['id'];
$quizData['title'] = $record['title'];
$quizData['description'] = $record['description'];
$quizData['path'] = $record['path'];
$quizData['questions'] = array();
}
if (!isset($quizData['questions'][$record['question_id']])) {
$quizData['questions'][$record['question_id']]['text'] = $record['question_text'];
$quizData['questions'][$record['question_id']]['type'] = $record['answer_type'];
$quizData['questions'][$record['question_id']]['answer_choices'] = array();
$quizData['questions'][$record['question_id']]['answers'] = array();
}
if (!isset($quizData['questions'][$record['question_id']]['answers'][$record['answer_id']])) {
$quizData['questions'][$record['question_id']]['answer_choices'][$record['answer_id']] = $record['answer_text'];
$quizData['questions'][$record['question_id']]['answers'][$record['answer_id']]['text'] = $record['answer_text'];
}
}
return count($quizData) > 0 ? $quizData : false;
}
public static function saveQuiz($quizData, $params) {
$uvisQuizUserObj = new UvisQuizUser();
$uvisQuizUserObj->setQuizId($quizData['id']);
$uvisQuizUserObj->setName($params['name']);
$uvisQuizUserObj->setEmail($params['email']);
$uvisQuizUserObj->save();
foreach ($quizData['questions'] as $questionId => $question) {
if(isset($params['question_'.$questionId]) && $params['question_'.$questionId] != ''){
$uvisQuizUserAnswerObj = new UvisQuizUserAnswer();
$uvisQuizUserAnswerObj->setQuizUserId($uvisQuizUserObj->getId());
$uvisQuizUserAnswerObj->setQuiestionId($questionId);
if($question['type'] == 'free_text'){
$uvisQuizUserAnswerObj->setFreeTextAnswer($params['question_'.$questionId]);
$uvisQuizUserAnswerObj->setPath($params['path']);
}
else{
$uvisQuizUserAnswerObj->setAnswerId($params['question_'.$questionId]);
}
$uvisQuizUserAnswerObj->save();
}
}
return $uvisQuizUserObj;
}
}
QuizCustomForm:
<?php
class UvisQuizCustomForm extends sfForm {
public function configure() {
$mimeTypes = array('application/pdf', 'application/x-pdf', 'application/rtf',
'application/vnd.oasis.opendocument.text', 'application/msword',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/x-msword', 'text/plain');
$this->widgetSchema['name'] = new sfWidgetFormInput(array(), array('class' => 'form-control'));
$this->widgetSchema['email'] = new sfWidgetFormInput(array(), array('class' => 'form-control'));
$this->widgetSchema['phone'] = new sfWidgetFormInput();
$this->validatorSchema['name'] = new sfValidatorString(array('max_length' => 64, 'required' => true, 'trim' => 'both'), array('required' => 'Name is required', 'max_length' => 'Maximum %max_length% characters allowed'));
$this->validatorSchema['email'] = new sfValidatorEmail(array('max_length' => 255, 'required' => true, 'trim' => 'both'), array('required' => 'Email is required', 'max_length' => 'Maximum %max_length% characters allowed', 'invalid' => 'Invalid email'));
$this->validatorSchema['phone'] = new sfValidatorRegex(array('pattern' => '/^[0-9\-]+$/', 'required' => false), array('invalid' => 'Invalid phone number'));
foreach ($this->options['questions'] as $questionId => $question) {
if($question['type'] == 'multiple'){
$this->widgetSchema['question_' . $questionId] = new sfWidgetFormChoice(array('choices' => $question['answer_choices'], 'expanded' => true));
$this->validatorSchema['question_' . $questionId] = new sfValidatorChoice(array('required' => false, 'choices' => array_keys($question['answer_choices'])), array('invalid' => 'Invalid option selected'));
} else {
$this->widgetSchema['path'] = new sfWidgetFormInputFile(array(
'label' => 'Upload File',
));
$this->setValidator('path', new sfValidatorFile(array(
'required' => false,
'path' => sfConfig::get('sf_upload_dir').'/uvis_front_user_files',
'mime_types' => $mimeTypes,
)));
$this->widgetSchema['question_' . $questionId] = new sfWidgetFormTextarea(array(), array('cols' => 50, 'rows' => 4));
$this->validatorSchema['question_' . $questionId] = new sfValidatorString(array('required' => false));
}
}
$this->widgetSchema['quiz_user_id'] = new sfWidgetFormInputHidden();
$this->validatorSchema['quiz_user_id'] = new sfValidatorPropelChoice(array('model' => 'UvisQuizUser', 'column' => 'id', 'required' => false));
$decorator = new sfWidgetFormSchemaFormatterMain($this->widgetSchema, $this->validatorSchema);
$this->widgetSchema->addFormFormatter('custom', $decorator);
$this->widgetSchema->setFormFormatterName('custom');
$this->widgetSchema->setNameFormat('UvisQuizFrontForm[%s]');
}
}
Just give write permission to the folder and check
Related
I am in the learning stage in php.Please help me with my update form.Advanced thanks. I have a form to update any user information with a button "Save" and "Reset" button.I update any information the version number increase.But the problem is when i do not update any information and click on "Save" button the version number increases.It should not increase.I am giving my Controller and form code....
public function actionCreate()
{
$model=new CvUpload;
$model2=new CvUpload;
$UserType=new UserType;
$CvHistory=new CvHistory;
$this->performAjaxValidation($model);
if(!empty($_POST))
{
$id = $_POST['CvUpload']['user_id'];
$cv_type = $_POST['CvUpload']['cv_type'];
$criteria = new CDbCriteria();
$criteria->condition = "user_id = $id AND is_current='yes' AND cv_type='$cv_type'";
$CvUploadmodel = CvUpload::model()->find($criteria);
if(!empty($CvUploadmodel))
{
$CvUploadmodel->is_current='no';
$CvUploadmodel->status='inactive';
if($CvUploadmodel->save(false)){
$model->attributes=$_POST['CvUpload'];
$model->upload_date = new CDbExpression("NOW()");
$model->update_date = new CDbExpression("NOW()");
$model->version_id = $CvUploadmodel->version_id+1;
if($model->save(false))
{
$CvHistory->cv_id = $model->cv_id;
$CvHistory->user_id = $model->user_id;
$CvHistory->job_title_id = $model->job_title_id;
$CvHistory->cv_type = $model->cv_type;
$CvHistory->version_id = $model->version_id;
$CvHistory->file_name = $model->file_name;
$CvHistory->upload_date = $model->upload_date;
$CvHistory->update_date = $model->update_date;
$CvHistory->is_current = $model->is_current;
$CvHistory->status = $model->status;
if($CvHistory->save(false))
{
$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
}
else
{
$model->attributes=$_POST['CvUpload'];
$model->upload_date = new CDbExpression("NOW()");
$model->update_date = new CDbExpression("NOW()");
$model->version_id=1;
if($model->save())
{
$CvHistory->cv_id = $model->cv_id;
$CvHistory->user_id = $model->user_id;
$CvHistory->job_title_id = $model->job_title_id;
$CvHistory->cv_type = $model->cv_type;
$CvHistory->version_id = $model->version_id;
$CvHistory->file_name = $model->file_name;
$CvHistory->upload_date = $model->upload_date;
$CvHistory->update_date = $model->update_date;
$CvHistory->is_current = $model->is_current;
$CvHistory->status = $model->status;
if($CvHistory->save(false))
{
$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
}
$this->render('create',array(
'model'=>$model,
'UserType'=>$UserType,
'CvHistory'=>$CvHistory,
));
}
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$CvHistory=new CvHistory;
if(isset($_POST['CvUpload']))
{
$model->attributes=$_POST['CvUpload'];
if($model->save())
{
$criteria = new CDbCriteria();
$criteria->condition = "cv_id = $model->cv_id AND is_current = 'yes'";
$CvHistory = CvHistory::model()->find($criteria);
$CvHistory->is_current = 'no';
$CvHistory->status = 'inactive';
if($CvHistory->save(false))
{
$new_CvHistory=new CvHistory;
$new_CvHistory->cv_id = $model->cv_id;
$new_CvHistory->user_id = $model->user_id;
$new_CvHistory->job_title_id = $model->job_title_id;
$new_CvHistory->cv_type = $model->cv_type;
$new_CvHistory->version_id = $CvHistory->version_id+1;
$model->version_id = $new_CvHistory->version_id ;
$new_CvHistory->file_name = $model->file_name;
$new_CvHistory->upload_date = $model->upload_date;
$new_CvHistory->update_date = new CDbExpression("NOW()");
$model->update_date = $new_CvHistory->update_date ;
$new_CvHistory->status = $model->status;
$new_CvHistory->is_current = "yes";
$new_CvHistory->save(false);
$model->save(false);
if($new_CvHistory->save(false))$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
$this->render('update',array(
'model'=>$model,
'CvHistory'=>$CvHistory,
));
}
MY form button code:
<style>
#type {
background-color:#f5f5f5;
font-family: 'Arial';
font-size: 20px;
text-decoration: none;
color:#b2b2b2;
border:none;
float: right;
}
div.form label {
display: block;
font-size: 1em;
font-weight: bold;
}
.types-add{
float: right;
}
#type:hover {
border: none;
}
</style>
<?php if (Yii::app()->user->hasFlash('created')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('created'); ?>
</div>
<?php endif; ?>
<div class="form">
<?php $form=$this->beginWidget(
'booster.widgets.TbActiveForm',
array(
'id'=>'CvUpload-form',
'type' => 'horizontal',
'htmlOptions' => array(
'class' => 'well',
'enctype' => 'multipart/form-data',
)
));
?>
<fieldset>
<h1 align="center">CV Upload</h1>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php
$criteria=new CDbCriteria();
echo $form->dropDownListGroup(
$model,
'user_id',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => CHtml::listData(User::model()->findAll($criteria), 'id', 'user_id'),
'dataProvider'=>$model->searchByUserId(Yii::app()->user->getId()),
'htmlOptions' => array('prompt'=>'Select'),
)
)
); ?>
</div>
<div class="row" id="jobTitle">
<?php
$criteria = new CDbCriteria;
$criteria->condition = "status= 'active'";
echo $form->dropDownListGroup(
$model,
'job_title_id',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => CHtml::listData(JobTitle::model()->findAll($criteria), 'id', 'name'),
'htmlOptions' => array('prompt'=>'Select job title'),
)
)
); ?>
</div>
<?php echo CHtml::form($this->createUrl('uploadreport'), 'post', array('enctype'=>'multipart/form-data'));?>
<label class="col-sm-3 control-label required" for="CvUpload_file_name">
Upload File
</label>
<div class="row" id="file_upload" style="margin-left:20%; margin-bottom:2%;">
<?php
$this->widget('CMultiFileUpload',array(
'name' => 'files',
'accept' => 'doc|docx|pdf',
'max' => 1,
'htmlOptions' => array('size' => 25),
));
echo CHtml::htmlButton('Upload',array(
'onclick'=>'javascript: send();', // on submit call JS send() function
'id'=> 'post-submit-btn', // button id 'newcreate'
'class'=>'btn btn-primary',
));
?>
</div>
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
<script src="http://code.jquery.com/jquery-migrate-1.2.0.js"></script>
<script>
function send(){
var formData = new FormData($("#CvUpload-form")[0]);
$.ajax({
url: '<?php echo Yii::app()->createUrl("CvUpload/upload"); ?>',
type: 'POST',
data: formData,
datatype:'json',
beforeSend: function() {
},
success: function (data) {
$("#CvUpload_file_name").val(data);
},
complete: function() {
},
error: function (data) {
alert("There may a error on uploading. Try again later");
},
cache: false,
contentType: false,
processData: false
});
return false;
}
</script>
<div class="row" id="file_name">
<?php echo $form->textFieldGroup(
$model,'file_name',
array(
'wrapperHtmlOptions' => array(
'class'=> 'col-sm-5',
),
)
);
?>
</div>
<div class="row" id="statustype">
<?php
$status = array('active'=>'Active', 'inactive'=>'Inactive');
echo $form->dropDownListGroup(
$model,
'status',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => $status,
'htmlOptions' => array('prompt'=>'Select a status'),
)
)
); ?>
</div>
<div class="row" id="statustype">
<?php
$is_current = array('yes'=>'Yes', 'no'=>'No');
echo $form->dropDownListGroup(
$model,
'is_current',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => $is_current,
'htmlOptions' => array('prompt'=>'Select a status'),
)
)
); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array(
'class'=>'btn btn-primary',
'style'=>"position:relative; margin-left:25%",
'id'=> 'yt1', // button id
)); ?>
</div>
</fieldset>
<?php $this->endWidget(); ?>
</div><!-- form -->
<!--/*/*
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'cv-upload-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'user_id'); ?>
<?php echo $form->textField($model,'user_id',array('size'=>20,'maxlength'=>20)); ?>
<?php echo $form->error($model,'user_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'upload_date');enter code here ?>
<?php echo $form->textField($model,'upload_date'); ?>
<?php echo $form->error($model,'upload_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'file_name'); ?>
<?php echo $form->textField($model,'file_name',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'file_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'file_location'); ?>
<?php echo $form->textField($model,'file_location',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'file_location'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
If you don't change form values, it doesn't mean that this data wouldn't be sended to server.
Here at least button save will sended, so this case will always true:
if(!empty($_POST))
You didn't show whole form, but I suggest that fields user_id and cv_type has values (no mater values where changed or not, if form has fields they will be submited)
$id = $_POST['CvUpload']['user_id'];
$cv_type = $_POST['CvUpload']['cv_type'];
That's why model $CvUploadmodel = CvUpload::model()->find($criteria); loads and increament version_id
I am new in yii framework. I am doing update operation using yii framework. I have controller with name sitecontroller.php, model jobseekerprofile.php, view personal.php. My table is job_seeker_profile with fields id,user_id,contact_no,gender,dob,mstatus,address.I can't update data by form posting.
My controller is sitecontroller.php
class SiteController extends Controller
{
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model = new jobseekerprofile();
$model = jobseekerprofile::model()->find(array(
'select' => 'contact_no,address', "condition" => "user_id=$user_id",
'limit' => 1,));
$model = $this->loadModel($user_id);
if (isset($_POST['jobseekerprofile'])) {
$model->attributes = $_POST['jobseekerprofile'];
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
}
public function loadModel($user_id)
{
echo $model = jobseekerprofile::model()->findByPk($user_id);
if ($model === null)
throw new CHttpException(404, 'The requested page does not exist.');
return $model;
}
}
view-personal.php
<div class="form">
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'login-form',
'enableClientValidation' => false,
'htmlOptions' => array(),
'clientOptions' => array(
'validateOnSubmit' => true
),
)); ?>
<?php
foreach (Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model, 'Contact No'); ?>
<?php echo $form->textField($model, 'contact_no'); ?>
<?php echo $form->error($model, 'contact_no'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'Address'); ?>
<?php echo $form->textField($model, 'address'); ?>
<?php echo $form->error($model, 'address'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save'); ?>
</div>
<?php $this->endWidget(); ?>
model-jobseekerprofile.php
rules in model
public function rules()
{
return array(
array('contact_no,gender,dob,address,mstatus','required'),
);
}
Anybody help me?
You need to use uppercases.
Jobseekerprofile.php and $model = new Jobseekerprofile(); at least, I'd even call it: JobseekerProfile.php and $model = new JobseekerProfile(); or something.
Example controller (not tested):
public function actionPersonal($id) {
$model = Jobseekerprofile::model()->findByPk($id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['Jobseekerprofile'];
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('personal', array(
'model' => $model,
));
}
Also you could use the Gii posibilities of Yii for these standard forms. It will generate forms based on your database and the relations in it.
I have two tables in database profile_fields and profile_fields_values.
Table profile_fields has columns
id
fieldname
fieldtitle
fieldtype
orderby
required
published
Table profile_field_values has columns
id
field_id
user_id
field_value
Here I have to create a dynamic profile management.
How do I show dynamic forms in Yii?
You need to use Form Builder, it has plenty of example how to construct your form using an array. It also supports sub-forms. Just follow the examples from the linked tutorial, content it's to long to be referenced here.
Update:
class LoginForm extends CFormModel
{
public $username;
public $password;
}
$form = new LoginForm();
$form->validatorList->add(
CValidator::createValidator('required', $form, 'username, password')
);
or another example:
class SomeModel
{
public $orders;
public function rules()
{
return array(
array('orders', 'validateOrders'),
);
}
public function validateOrders($attribute, $params)
{
foreach($this->orders as $order)
if (empty($order)) {
$this->addError('orders', 'There is an empty order');
break;
}
}
}
A more broader example is on forum.
I am trying to build this dynamic profile management let me know my approach is my approach is right?
firstly i have created a input form(_form) where user can input fieldtype,fieldname,fieldtitle and field default value and etc which can be save in database table (profile_fields).In this fieldtype is bydefault set and user choose it from dropdownlist As like in the below form.
<?php
/* #var $this ProfileManagerController */
/* #var $model ProfileFields */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'profile-fields-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'location'); ?>
<?php echo $form->dropDownList($model,'location',CHtml::listData(Countries::model()->findAll('',array('orderby' => 'countryName ASC')),'countryCode','countryName'), array('empty' => array("*" => 'For All Countries'))); ?>
<?php echo $form->error($model,'location'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'profile_type'); ?>
<?php echo $form->dropDownList($model,'profile_type',Yii::app()->params['userRoles'], array('empty' => array("*" => 'For All users')), array($model->profile_type)); ?>
<?php //echo $form->dropDownList($model, 'profile_type', Yii::app()->params['userRoles'], array($model->profile_type)); ?>
<?php echo $form->error($model,'profile_type'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'section'); ?>
<?php echo $form->dropDownList($model,'section',array('profile'=>'profileSection','basicdetails'=>'BasicDetails','contactdetails'=>'ContactDetails','imagedetails'=>'ImageDetails','clientdetails'=>'ClientDetails','tagdetails'=>'TagDetails','otherdetails'=>'OtherDetails','alldetails'=>'AllDetails')); ?>
<?php echo $form->error($model,'section'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field_name'); ?>
<?php echo $form->textField($model,'field_name',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'field_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field_title'); ?>
<?php echo $form->textField($model,'field_title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'field_title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field_type'); ?>
<?php echo $form->dropDownList($model,'field_type',array('text' => 'Text','date' => 'Date','email' => 'Email', 'radio' => 'Radio','multiselect' => 'Multi Select Dropdown List','file'=>'File','checkbox'=>'CheckBox','hidden'=>'Hidden','select'=>'Dropdownlist','password'=>'Password','checkboxlist'=>'Checkboxlist','radiolist'=>'Radiolist','textarea'=>'TextArea'),array('options' => array($model->field_type => array('selected' => true)))); ?>
<?php echo $form->error($model,'field_type'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field_default_value'); ?>
<?php echo $form->textArea($model,'field_default_value',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'field_default_value'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'required'); ?>
<?php echo $form->dropDownList($model, 'required', array('1' => 'Yes', '0' => 'No')); ?>
<?php echo $form->error($model,'required'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'published'); ?>
<?php echo $form->dropDownList($model, 'published', array('1' => 'Yes', '0' => 'No')); ?>
<?php echo $form->error($model,'published'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'order_by'); ?>
<?php echo $form->textField($model,'order_by'); ?>
<?php echo $form->error($model,'order_by'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
secondly I have created a view index file which will show dynamically what type of fieldstypes and fieldsname and field title are set by the user in profile_field table and call the extension created by me and then another user can input accordingly .and these values are save in profile_field_values table .
----------index file---------------
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'completeProfile-form',
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'enableAjaxValidation' => false,
'clientOptions' => array('validataOnSubmit' => true),
'enableClientValidation' => true,
));
?>
<?php
if (!empty($field_data)) {
foreach ($field_data as $field) {
$selectedOptions = '';
$def_value='';
$field_name = $field->field_name; // required field
$field_type = $field->field_type; // required field
$field_id = $field->id; // required field
//for validation
$req = $field->required == 1 ? 'required' : ''; // required if using validation
$email = $field->field_type == 'email' ? 'email' : ''; // required if using validation
$password = $field->field_type == 'password' ? 'password' : ''; // required if using validation
$class = array($req, $email, $password); // class must be array type, if no class found, send empty array
//values present in ProfileFieldsValues to populate
$value = ProfileFieldsValues::model()->findByAttributes(array('user_id' => Yii::app()->user->id, 'field_id' => $field->id));
// set html options
$htmlOptions = array();
$htmlOptions['class'] = implode(" ", $class);
$htmlOptions['value'] = $value ? $value->field_value : '';
// field array - Must SET
$fieldArray = array();
$fieldArray['model'] = $field;
$fieldArray['form'] = $form;
$fieldArray['field_type'] = $field_type;
$fieldArray['field_name'] = $field_name;
$fieldArray['field_id'] = $field_id;
$fieldArray['default_value'] = $value ? $value->field_value : $field->field_default_value;
//If input type field is dropdowlist for selecttion
if($field_type == 'select' ){
if(!empty($field->field_default_value)){
$my_string = preg_replace(array('/\n/'), '#PH#', $field->field_default_value );
$my_array = explode('#PH#', $my_string);
foreach($my_array as $my_arr){
$def=explode('|',$my_arr);
$def_value[$def[0]]=$def[1];
}
$fieldArray['select_box_array']=$def_value;
}else{
$fieldArray['select_box_array'] =$country;
}
$htmlOptions['prompt'] = 'SELECT ANY';
$value ? $htmlOptions['options']=array($value->field_value=>array('selected'=>'true')): $htmlOptions['prompt'] = 'SELECT ANY';
}
//if input type field is multiple select dropdownlist
if( $field_type == 'multiselect'){
if(!empty($field->field_default_value)){
$my_string = preg_replace(array('/\n/'), '#PH#', $field->field_default_value );
$my_array = explode('#PH#', $my_string);
foreach($my_array as $my_arr){
$def=explode('|',$my_arr);
$def_value[$def[0]]=$def[1];
}
$fieldArray['select_box_array']=$def_value;
}else{
$fieldArray['select_box_array'] =$country;
}
$htmlOptions['prompt'] = 'SELECT Multiple';
if(!empty($value)){
$field_valu= explode(',',$value->field_value);
foreach($field_valu as $eachValue){
$selectedOptions[$eachValue] = array('selected'=>'selected');
}
$htmlOptions['options']= $selectedOptions;
}
}
// if input type field is radio button
if ($field_type == 'radiolist') {
$fl = ProfileFieldsValues::model()->findByAttributes(array('field_id' => $field->id, 'user_id' => Yii::app()->user->id));
if(!empty($field->field_default_value)){
$my_string = preg_replace(array('/\n/'), '#PH#', $field->field_default_value );
$my_array = explode('#PH#', $my_string);
foreach($my_array as $my_arr){
$def=explode('|',$my_arr);
$def_value[$def[0]]=$def[1];
}
$fieldArray['radio_box_array']=$def_value;
}else{
$fieldArray['radio_box_array'] =array('hello','bye');
}
$value = $fl ? $fl->field_value : 0;
$htmlOptions = array('labelOptions' => array('style' => 'display:inline'), 'separator' => ' ','value' => $value);
}
//if input type field is checkbox list
if ($field_type == 'checkboxlist') {
$fl = ProfileFieldsValues::model()->findByAttributes(array('field_id' => $field->id, 'user_id' => Yii::app()->user->id));
if(!empty($field->field_default_value)){
$my_string = preg_replace(array('/\n/'), '#PH#', $field->field_default_value );
$my_array = explode('#PH#', $my_string);
foreach($my_array as $my_arr){
$def=explode('|',$my_arr);
$def_value[$def[0]]=$def[1];
}
$fieldArray['check_box_array']=$def_value;
}else{
$fieldArray['check_box_array'] =array('hello','bye');
}
$value = $fl ? (array)explode(",",$fl->field_value) : array(0);
$htmlOptions = array('labelOptions' => array('style' => 'display:inline'), 'separator' => ' ','value' => $value );
}
//if input type field is file
if ($field_type == 'file') {
$files = ProfileFieldsValues::model()->findByAttributes(array('field_id' => $field->id, 'user_id' => Yii::app()->user->id));
if(isset($files->field_value)){
echo CHtml::image(Yii::app()->request->baseUrl . '/images/user_images/' .$files->field_value, 'Image', array('class' => 'img-polaroid', 'width' => 200));
}
}
$fieldArray['htmlOptions'] = $htmlOptions;
if ($field->published == '1') {
if($field->field_type == 'checkbox' || $field->field_type == 'radio' ){ ?>
<div class="row">
<?php $this->widget('ext.dynamicFields.EDynamicFields', $fieldArray); ?>
<?php echo $field->field_title; ?>
<?php echo $form->error($field, $field->field_title); ?>
</div>
<?php }else{ ?>
<div class="row">
<?php echo $form->labelEx($field, $field->field_title); ?>
<?php $this->widget('ext.dynamicFields.EDynamicFields', $fieldArray); ?>
<?php echo $form->error($field, $field->field_title); ?>
</div>
<?php } ?>
<?php } ?>
<?php } ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php
}
$this->endWidget();
?>
</div><!-- form -->
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getBaseUrl(true) . '/js/jquery.validate.js'); ?>
<script type="text/javascript">
$("#completeProfile-form").validate({
});
</script>
I have created a extension for various input type fields like
1.text
2.email textbox
3.hidden input type field
4.textarea
5.dropdownlist
6. multiple select dropdownlist
7.password textfield
8.file
9.radiolist
10.radio button
11 checkbox
12checkboxlist
13 date field
<?php
/**
* Description of EDynamicFields
* It will show dynamic fields
*
* #author Gaurav Parashar
*/
class EDynamicFields extends CWidget {
public $field_type;
public $field_name;
public $field_id;
public $default_value;
public $select_box_array = array();
public $radio_box_array = array();
public $check_box_array = array();
public $htmlOptions = array();
public $model;
public $form;
public $select;
public function run() {
switch ($this->field_type) {
case 'text':
echo $this->form->textField($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'email':
echo $this->form->textField($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'hidden':
echo $this->form->hiddenField($this->model, "field_name[$this->field_type][$this->field_id]", $this->default_value);
break;
case 'textarea':
echo $this->form->textArea($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'select':
echo $this->form->dropDownList($this->model, "field_name[$this->field_type][$this->field_id]", $this->select_box_array, $this->htmlOptions);
break;
case 'password':
echo $form->passwordField($model,'password',$this->htmlOptions);
break;
case 'multiselect':
$newarr = array_merge($this->htmlOptions, array('multiple' => 'multiple'));
echo $this->form->dropDownList($this->model, "field_name[$this->field_type][$this->field_id]", $this->select_box_array, $newarr);
break;
case 'file':
echo $this->form->fileField($this->model, "field_name[$this->field_type][$this->field_id]" ,$this->htmlOptions);
break;
case 'radio':
echo $this->form->radioButton($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'radiolist':
echo CHtml::radioButtonList("ProfileFields[field_name][$this->field_type][$this->field_id]",$this->htmlOptions['value'],$this->radio_box_array,$this->htmlOptions);
break;
case 'checkbox':
echo $this->form->checkBox($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'date':
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'attribute' => "field_name[$this->field_type][$this->field_id]",
'model' => $this->model,
'htmlOptions'=>array(
'class'=>'required',
),
'options' => array(
'dateFormat' => 'yy-mm-dd',
'maxDate' => 'new Date()', // One month ahead
//'minDate' => '-50y', // Today
'changeMonth' => true,
'changeYear' => true,
'yearRange'=>'2000:2099',
'minDate' => '2000-01-01', // minimum date
'maxDate' => '2099-12-31',
)
));
break;
case 'checkboxlist':
echo CHtml::checkBoxList("ProfileFields[field_name][$this->field_type][$this->field_id]",$this->htmlOptions['value'],$this->check_box_array,$this->htmlOptions);
break;
}
}
}
I have a CActiveForm which when submitted should make a second CActiveForm become visible. I know how to change the htmlOptions of the form when its created but not how to access it via the controller.
My View with two forms. The second form has visibility:hidden
<div class="form">
<?php
$numberForm = $this->beginWidget('CActiveForm', array(
'id' => 'addnumber-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<p class="note"><?php echo UserModule::t('Fields with <span class="required">*</span> are required.'); ?></p>
<?php echo $numberForm->errorSummary($numberModel); ?>
<div class="row">
<?php echo $numberForm->labelEx($numberModel, 'number'); ?>
<?php echo $numberForm->textField($numberModel, 'number'); ?>
<?php echo $numberForm->error($numberModel, 'number'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Verify"), array(
"class" => "btn btn-success"
));
?>
</div>
<?php $this->endWidget(); ?>
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: hidden"),
));
?>
<?php echo $verifyForm->errorSummary($verifyModel); ?>
<p>A authorisation code has been sent to your phone. Please enter it below. If you don't receive a text message make sure you entered your number correctly and try again</p>
<div class="row">
<?php echo $verifyForm->labelEx($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->textField($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->error($verifyModel, 'authcodeUser'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Confirm"), array(
"class" => "btn btn-success"
));
?>
<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
My controller for these forms
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel));
}
It looks like you could just create a new variable for whether or not to show the second form and then pass it to the view. Here is your controller:
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
$formVisibility = "hidden";
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
$formVisibility = "visible";
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel, 'formVisibility' => $formVisibility));
}
And here is the first part of your second form:
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: ".$formVisibility),
));
?>
[edit] To make sure I am answering your question, I should add that I've never seen any way of changing the htmlOptions from the controller directly. That's why I proposed this solution instead.
Does anyone have experience of uploading a series of files to a web server with FuelPHP?
My current setup adds content to a database from a Form, but I'd like to process images at this point too - so basically move them to my web server when submitting a form.
Is this simple to do?
I have my 'action_add()' method in my controller, but not sure how to update it to loop through all my file fields and move files.
public function action_add()
{
$val = Model_Article::validate('add_article');
if ($val->run())
{
$status = (Input::post('save_draft') ? 0 : 1);
if ( ! $val->input('category_id'))
{
$category_id = null;
}
else
{
$category_id = $val->validated('category_id');
}
$article = new Model_Article(array(
'user_id' => $this->user_id,
'category_id' => $category_id,
'title' => $val->validated('title'),
'body' => $val->validated('body'),
'published' => $status,
));
if ($article->save())
{
Session::set_flash('success', 'Article successfully added.');
}
else
{
Session::set_flash('error', 'Something went wrong, '.
'please try again!');
}
Response::redirect('articles/add');
}
$this->template->title = 'Add Article';
$this->template->content = View::forge('articles/add')
->set('categories', Model_Category::find('all'), false)
->set('val', Validation::instance('add_article'), false);
}
My Form:
<h2>Add an Article</h2>
<p>Publish a new article by filling the form below.</p>
<div class="options">
<div class="option">
<?php echo Html::anchor('articles', 'View Articles'); ?>
</div>
<div class="option">
<?php echo Html::anchor('categories/add', 'Add a Category'); ?>
</div>
</div>
<?php echo $val->show_errors(); ?>
<?php echo Form::open(array('enctype' => 'multipart/form-data')); ?>
<?php $select_categories = array(null => 'Uncategorized'); ?>
<?php foreach ($categories as $category): ?>
<?php $select_categories[$category->id] = $category->name; ?>
<?php endforeach; ?>
<div class="input select">
<?php echo Form::label('Category', 'category_id'); ?>
<?php echo Form::select('category_id', e($val->input('category_id')),
$select_categories); ?>
</div>
<div class="input text required">
<?php echo Form::label('Title', 'title'); ?>
<?php echo Form::input('title', e($val->input('title')),
array('size' => '30')); ?>
</div>
<div class="input textarea required">
<?php echo Form::label('Body', 'body'); ?>
<?php echo Form::textarea('body', e($val->input('body')),
array('rows' => 4, 'cols' => 40)); ?>
</div>
<div class="input textarea required">
<?php echo FORM::file('filename'); ?>
</div>
<div class="input submit">
<?php echo Form::submit('add_article', 'Publish'); ?>
<?php echo Form::submit('save_draft', 'Save Draft'); ?>
</div>
<?php echo Form::close(); ?>
Many thanks for any pointers.
Okay I can give you some instruction.
First fuelphp upload documentation
Hope it helps sorry if there are typos in it
public function action_add()
{
$val = Model_Article::validate('add_article'); //<-- maybe its just me but I never saw any similar to this in fuelphp sorry about this if I'm wrong
// if your form validation is okay than continue with everyhing else
if ($val->run())
{
$article = Model_Article::forge();
// Custom configuration for this upload
$config = array(
'path' => DOCROOT.DS.'foldername/tomove/your/images',
'randomize' => true,
'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'),
);
Upload::process($config);
// if a valid file is passed than the function will save, or if its not empty
if (Upload::is_valid())
{
// save them according to the config
Upload::save();
//if you want to save to tha database lets grab the file name
$value = Upload::get_files();
$article->your_file_input_name = $value[0]['saved_as'];
}
$status = (Input::post('save_draft') ? 0 : 1);
if ( ! $val->input('category_id'))
{
$category_id = null;
}
else
{
$category_id = $val->validated('category_id');
}
$article->user_id = $this->user_id;
$article->category_i = $category_id;
$article->title = $val->validated('title');
$article->body = $val->validated('body');
$article->published = $status;
if ($article->save())
{
Session::set_flash('success', 'Article successfully added.');
}
else
{
Session::set_flash('error', 'Something went wrong, '.
'please try again!');
}
Response::redirect('articles/add');
}
$this->template->title = 'Add Article';
$this->template->content = View::forge('articles/add')
->set('categories', Model_Category::find('all'), false)
->set('val', Validation::instance('add_article'), false);
}