Related
How to retrieve the array values from multiples checkbox? I have problem when I retrieve value array and echo the value. I get this error
Severity: Warning
Message: in_array() expects parameter 2 to be array, string given
Filename: page/update.php.
Please, could you help me again? Thank you.
You find three files: View, Model and Controller. Please check where I wrong...
UPDATE.PHP:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="row">
<div class="col-sm-12">
<?php echo form_open('page_controller/update_page_post'); ?>
<div class="form-group">
<div class="row">
<div class="col-sm-3 col-xs-12">
<label><?php echo trans('subcategory'); ?></label>
</div>
</div><div class="col-xm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped" role="grid">
<tbody>
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
//if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach ($array_of_values as $item) {
if(in_array($valuesub,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?></tr>
</tbody>
</table>
</div>
</div>
</div>
PAGE_CONTROLLER.PHP
public function update_page_post()
{
//validate inputs
$this->form_validation->set_rules('title', trans("title"), 'required|xss_clean|max_length[500]');
if ($this->form_validation->run() === false) {
$this->session->set_flashdata('errors', validation_errors());
$this->session->set_flashdata('form_data', $this->page_model->input_values());
redirect($this->agent->referrer());
} else {
//get id
$id = $this->input->post('id', true);
$redirect_url = $this->input->post('redirect_url', true);
if (!$this->page_model->check_page_name()) {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_page_slug_error"));
redirect($this->agent->referrer());
exit();
}
if ($this->page_model->update($id)) {
$this->session->set_flashdata('success', trans("msg_updated"));
if (!empty($redirect_url)) {
redirect($redirect_url);
} else {
redirect(admin_url() . 'pages');
}
} else {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_error"));
redirect($this->agent->referrer());
}
}
}
PAGE_MODEL.PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Page_model extends CI_Model
{
//input values
public function input_values()
{
$checkbox = implode(',', $this->checkBox());
$data = array(
'lang_id' => $this->input->post('lang_id', true),
'title' => $this->input->post('title', true),
'slug' => $this->input->post('slug', true),
'page_description' => $this->input->post('page_description', true),
'page_keywords' => $this->input->post('page_keywords', true),
'page_content' => $this->input->post('page_content', false),
'page_order' => $this->input->post('page_order', true),
'parent_id' => $this->input->post('parent_id', true),
'page_active' => $this->input->post('page_active', true),
'title_active' => $this->input->post('title_active', true),
'breadcrumb_active' => $this->input->post('breadcrumb_active', true),
'right_column_active' => $this->input->post('right_column_active', true),
'need_auth' => $this->input->post('need_auth', true),
'howmany_people' => $this->input->post('howmany_people', true),
'difficulty' => $this->input->post('difficulty', true),
'howmany_time' => $this->input->post('howmany_time', true),
'location' => $this->input->post('location', true),
'subcat_recip_id' => $checkbox
);
return $data;
}
public function checkBox(){
$count = count($_POST['subcat_recip_id']);
for($n=0; $n<$count; $n++){
$checkbox[$n] = $_POST['subcat_recip_id'][$n];
}
return $checkbox;
}
//update page
public function update($id)
{
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
in your you view,
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
foreach ($array_of_values as $item) {
if(in_array($subcat_recip_id,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?>
</tr>
change to :
<tr>
<?php $valuesub = ($page->subcat_recip_id);
$array_of_values = explode(",", $valuesub); ?>
<td>
<?php foreach ($array_of_values as $item) :?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" <?=(in_array($subcat_recip_id,$item))?"CHECKED":""?>> <?=html_escape($item["title"]);?>'
<?php endforeach; ?>
</td>
<?=html_escape($valuesub)?>
</tr>
in model :
public function update($id){
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
change to :
public function update($id){
$data = $this->input_values();
if (empty($data["slug"])) {
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
please update if you getting error,
tq
Well, it remains a bug but with some changes yr last code works. The great problem is the loop, it re-load the $valuesub for how many times is the value. Ie. If the array is composed of three values, it reads three times the same value. Pls see the two screenshots: https://www.screencast.com/t/MfiEDhdFuX
I can't get this loop off !!
Code
<td>
<?php foreach ($menu_links as $item) :
$valuesub = ($page->subcat_recip_id);
$array_of_values = explode("," , $valuesub);
if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach($array_of_values as $dt): ?>
<?php //if(in_array($dt,$item)): ?>
<input type="checkbox" name="subcat_recip_id" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" <?=(in_array($dt,$item))?"CHECKED":""?>> <?=html_escape($item["title"]);?>
<?php endforeach; endif;?>
<?php endforeach; ?>
</td><?php echo html_escape($valuesub); ?>
How to get value form multiples checkbox and post array in codeigniter? I have problem when I get value post array and echo the value. I see only the value of the last checked checkbox. How to show post value when submit?
You find three files: view, Controller and Model. Please check where I wrong...
UPDATE.PHP:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="row">
<div class="col-sm-12">
<?php echo form_open('page_controller/update_page_post'); ?>
<div class="form-group">
<div class="row">
<div class="col-sm-3 col-xs-12">
<label><?php echo trans('subcategory'); ?></label>
</div>
</div><div class="col-xm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped" role="grid">
<tbody>
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
//if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach ($array_of_values as $item) {
if(in_array($subcat_recip_id,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?></tr>
</tbody>
</table>
</div>
</div>
</div>
PAGE_MODEL.PHP:
<?php class Page_model extends CI_Model
{
public function input_values()
{
$data = array(
'lang_id' => $this->input->post('lang_id', true),
'title' => $this->input->post('title', true),
'slug' => $this->input->post('slug', true),
'page_description' => $this->input->post('page_description', true),
'page_keywords' => $this->input->post('page_keywords', true),
'page_content' => $this->input->post('page_content', false),
'parent_id' => $this->input->post('parent_id', true),
'page_active' => $this->input->post('page_active', true),
'title_active' => $this->input->post('title_active', true),
'breadcrumb_active' => $this->input->post('breadcrumb_active', true),
'need_auth' => $this->input->post('need_auth', true),
'howmany_people' => $this->input->post('howmany_people', true),
'difficulty' => $this->input->post('difficulty', true),
'howmany_time' => $this->input->post('howmany_time', true),
'location' => $this->input->post('location', true),
'subcat_recip_id' => $this->input->post('subcat_recip_id')
for ($i=0; $i<count($menu_links); $i++)
{
echo $subcat_recip_id[$i];
}
);
return $data;
}
//add page
public function add()
{
$data = $this->page_model->input_values();
if (empty($data["slug"]))
{
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"]))
{
$data["slug"] = "page-" . uniqid();
}
}
return $this->db->insert('pages', $data);
}
//update page
public function update($id)
{
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
PAGE_CONTROLLER.PHP
* Add Page Post*/
public function add_page_post()
{
//validate inputs
$this->form_validation->set_rules('title', trans("title"), 'required|xss_clean|max_length[500]');
if ($this->form_validation->run() === false) {
$this->session->set_flashdata('errors', validation_errors());
$this->session->set_flashdata('form_data', $this->page_model->input_values());
redirect($this->agent->referrer());
} else {
if (!$this->page_model->check_page_name()) {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_page_slug_error"));
redirect($this->agent->referrer());
exit();
}
if ($this->page_model->add()) {
$this->session->set_flashdata('success', trans("page") . " " . trans("msg_suc_added"));
redirect($this->agent->referrer());
} else {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_error"));
redirect($this->agent->referrer());
}
}
}
I have tried this code
in your Page_model put this code.
public function input_values(){
$checkbox = implode(',', $this->checkBox());
$data = array(
'lang_id' => $this->input->post('lang_id', true),
'title' => $this->input->post('title', true),
'slug' => $this->input->post('slug', true),
'page_description' => $this->input->post('page_description', true),
'page_keywords' => $this->input->post('page_keywords', true),
'page_content' => $this->input->post('page_content', false),
'parent_id' => $this->input->post('parent_id', true),
'page_active' => $this->input->post('page_active', true),
'title_active' => $this->input->post('title_active', true),
'breadcrumb_active' => $this->input->post('breadcrumb_active', true),
'need_auth' => $this->input->post('need_auth', true),
'howmany_people' => $this->input->post('howmany_people', true),
'difficulty' => $this->input->post('difficulty', true),
'howmany_time' => $this->input->post('howmany_time', true),
'location' => $this->input->post('location', true),
'subcat_recip_id' => $checkbox
);
}
public function checkBox(){
$count = count($_POST['subcat_recip_id']);
for($n=0; $n<$count; $n++){
$checkbox[$n] = $_POST['subcat_recip_id'][$n];
}
return $checkbox;
}
hopefully it helps
This is what $menu_links is:
public function get_menu_links_by_lang()
{
$lang_id = $this->input->post('lang_id', true);
if (!empty($lang_id)):
$menu_links = $this->navigation_model->get_menu_links_by_lang($lang_id);
foreach ($menu_links as $item):
if ($item["type"] != "category" && $item["location"] == "header" && $item['parent_id'] == "0"):
echo ' <option value="' . $item["id"] . '">' . $item["title"] . '</option>';
endif;
endforeach;
endif;
}
I edited a code to insert new form page and I need this page to enter some values into DB. All works Ok and they inserted to DB, only the checkbox doesn't work or better it take only the value of the last checked checkbox and not all the checkbox checked! I have tried it in many ways but I can't do it alone. Sorry.
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;
}
}
}
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);
}
I am not being able to run validation on an array of input fields. When I submit the form, it is submitted OK (data is saved correctly), but without validation (no errors, no messages).
Any idea what I'm doing wrong?
My view:
<?php echo form_open('save', array('id' => 'form')); ?>
<?php foreach ($cars as $row): ?>
<table>
<tr>
<td>
<h2>
<?php echo $row->cars_name; ?>
</h2>
</td>
<th>
Number
</th>
<td>
<?php echo form_input("car[$row->cars_id][cars_number]", $row->cars_number); ?>
</td>
</tr>
<tr>
<td>
</td>
<th>
Registry
</th>
<td>
<?php echo form_input("car[$row->cars_id][cars_number_reg]", $row->cars_number_reg); ?>
</td>
</tr>
</table>
<?php endforeach; ?>
<?php echo form_close(); ?>
My config/form_validation.php:
'test/save' => array(
array(
'field' => 'car[]', // also tried car[][], but no go
'label' => 'Field',
'rules' => 'alpha|htmlspecialchars|trim'
),
),
My controller:
function save()
{
if ($this->form_validation->run() == FALSE) {
$json['success'] = '0';
$json['message'] = validation_errors();
echo json_encode($json);
} else {
$car = $this->input->post('car');
foreach ($car as $k => $v) {
$data['cars_number'] = $v['cars_number'];
$data['cars_number_reg'] = $v['cars_number_reg'];
$cars_id = $k;
$this->emergency_model->save($data, $cars_id);
}
$json['success'] = '1';
echo json_encode($json);
}
}
I suggest using a callback validation function like in this tutorial
in this tutorial
From the user guide form_validation
You must use the "exact" name for validation rules.
In your case validation rules should be generated in foreach, same as your view.
$validation_rules = array();
foreach($cars as $row){
$validation_rules[] = array( 'field'=>'car['.$row->cars_id.'][cars_number]',
'Field',
'rules' => 'alpha|htmlspecialchars|trim'
);
}
$this->form_validation->set_rules($validation_rules);
(note:this code was not tested)
I think you have to do this in controller instead of config.