Add get parameter to URL, using form_open function? - php

I tried to implement standard PHP logic for add, edit articles to blog, so i have add method:
public function add()
{
$this->load->model('admin/Blog_Model');
if (!empty($this->input->post())) {
$user = $this->Blog_Model->addPost($this->input->post());
}
$this->getForm();
}
edit method:
public function edit($id = '')
{
$this->load->model('admin/Blog_Model');
if (!empty($this->input->post())) {
var_dump($id); exit;
$user = $this->Blog_Model->editPost($this->input->post(), $id);
}
$this->getForm($id);
}
and getForm method:
public function getForm($id = '')
{
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
$data['formTitle'] = array(
'name' => 'title',
'id' => 'content-title',
'value' => isset($post['title']) ? $post['title'] : '',
'placeholder' => 'Заглавие',
'class' => 'form-control'
);
$data['formContent'] = array(
'name' => 'content',
'id' => 'content-blog',
'value' => isset($post['content']) ? $post['content'] : '',
'placeholder' => 'Съдържание',
);
$data['formButton'] = array(
'type' => 'submit',
'content'=> 'Изпрати',
'class'=> 'btn btn-primary btn-block btn-flat'
);
$data['head'] = $this->load->view('admin/head', NULL, TRUE);
$data['left_column'] = $this->load->view('admin/left_column', NULL, TRUE);
$this->load->view('admin/header', $data);
$this->load->view('admin/blog_form', $data);
$this->load->view('admin/footer');
}
and blog_form view with form:
<div class="box-body pad">
<?php echo form_open($action); ?>
<div class="box-body">
<div class="form-group">
<label for="content-title">Заглавие:</label>
<?php echo form_input($formTitle); ?>
</div>
<div class="form-group">
<label for="content_blog">Съдържание:</label>
<?php echo form_textarea($formContent); ?>
</div>
<div class="col-xs-12 col-md-3 pull-right">
<?php echo form_button($formButton); ?>
</div>
</div>
<?php echo form_close(); ?>
</div>
So .. everything works perfect, but i have problem with this part:
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
if it's edit i want to send id like GET parameter. I think the problem is there than i does not use standard GET parameters instead of site_url function, when i show all articles here:
<?php foreach ($posts as $post) { ?>
<tr>
<td><?php echo $post['id']; ?></td>
<td><?php echo $post['title']; ?></td>
<td><?php echo $post['content']; ?></td>
<td><div class="btn-group">
Редактирай
Изтрий
</div></td>
</tr>
<?php } ?>

Try to change
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
to
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit/'.$id; // pass $id to edit controller
} else {
$data['action'] = 'admin/blog/add';
}

Related

How to get value from checkbox and post array in codeigniter?

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.

Store value to variable Opencart

I think this is basic problem for open cart, but I cant fix it, in view I put 1 field head_text_field then i put to variable in controller then use var_dump for check value
This for View :
<?php echo $header; ?>
<div id="content">
<div class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<?php echo $breadcrumb['separator']; ?><?php echo $breadcrumb['text']; ?>
<?php } ?>
</div>
<?php if ($error_warning) { ?>
<div class="warning"><?php echo $error_warning; ?></div>
<?php } ?>
<?php if ($success) { ?>
<div class="success"><?php echo $success; ?></div>
<?php } ?>
<div class="box">
<div class="heading">
<h1><img src="view/image/product.png" alt="" /> <?php echo $heading_title; ?></h1>
<div class="buttons"><a onclick="$('#form').submit();" class="button"><?php echo $button_save; ?></a><?php echo $button_cancel; ?></div>
</div>
<div class="content">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form">
<table class="form">
<tr>
<td><span class="required">*</span> <?php echo $entry_head; ?></td>
<td><input type="text" name="head_text_field" value="<?php echo $head_text_field; ?>" placeholder="Input Head Text" size="40"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>
<?php echo $footer; ?>
Controller:
<?php
class ControllerItemItem extends Controller {
private $error = array();
public function index() {
$this->language->load('item/item');
$this->document->setTitle($this->language->get('heading_title'));
$this->getList();
}
protected function getList(){
if (isset($this->request->get['head_text_field'])){
$head_text_field = $this->request->get['head_text_field'];
var_dump($head_text_field); exit; // VAR_DUMP HERE
} else {
$head_text_field = null;
echo "FAILED"; // FAILED HERE
}
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('module/item', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => ' :: '
);
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['entry_head'] = $this->language->get('entry_head');
$this->data['button_save'] = $this->language->get('button_save');
$this->data['button_cancel'] = $this->language->get('button_cancel');
$this->data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL');
$this->data['action'] = $this->url->link('item/item/insert', 'token=' . $this->session->data['token'], 'SSL');
$this->data['token'] = $this->session->data['token'];
$this->template = 'item/item.tpl';
$this->children = array(
'common/header',
'common/footer'
);
$this->response->setOutput($this->render());
}
public function insert()
{
var_dump($head_text_field); exit;
}
}
?>
When I try input, result is FAILED?? Where I did mistake? for model I not call or use it right now in controller.
EDIT 1
Sorry i add function insert for make it not error (for button insert in controller bottom)
If you want to get any variable from opencart controller in your view then you need to pass this variable as below:
Controller File
if (isset($this->request->post['head_text_field'])){
$this->data['head_text_field'] = $this->request->get['head_text_field']; // Your variable
var_dump($this->data['head_text_field']); exit; // VAR_DUMP HERE
} else {
$this->data['head_text_field'] = null;
echo "FAILED"; // FAILED HERE
}
Now you can get head_text_field in your view file as $head_text_field.
Edit
public function insert()
{
if (($this->request->server['REQUEST_METHOD'] == 'POST')) {
echo $this->request->post['head_text_field']; // Your field value
}
}
$this->request->post['head_text_field']

string conversion error in array codeigniter

On my controller I have a error on this line 'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
When I refresh my page it throws the error Array to string conversion
A PHP Error was encountered Severity: Notice Message: Array to string
conversion Filename: user/users_group_update.php Line Number: 47
Not sure what to do on that because I need to add variable $controller in to $this->getId($controller);
What changes is best suited to make this work.
<?php
class Users_group_update extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user_group');
}
public function index() {
$data['title'] = "Users Group Update";
$controller_files = $this->getInstalled($this->uri->segment(3));
$data['controller_files'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
if ($files) {
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
$do_not_list = array(
'customer_total',
'dashboard',
'footer',
'header',
'login',
'logout',
'menu',
'online',
'permission',
'register',
'user_total'
);
if (!in_array($controller, $do_not_list)) {
$data['controller_files'][] = array(
'name' => $controller,
'installed' => in_array($controller, $controller_files),
'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
);
}
}
}
$this->load->view('template/user/users_group_form_update', $data);
}
public function getInstalled($name) {
$controller_data = array();
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $name);
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$controller_data[] = $result['controller'];
}
return $controller_data;
}
public function getId($controller) {
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $this->uri->segment(3));
$this->db->where('controller', $controller);
$query = $this->db->get();
return $query->row('user_group_id');
}
}
View
<?php echo Modules::run('admin/common/header/index');?>
<div id="wrapper">
<?php echo Modules::run('admin/common/menu/index');?>
<div id="page-wrapper" >
<div id="page-inner">
<?php
$data = array(
'class' =>
'form-horizontal',
'id' =>
'form-users-group'
);
echo form_open_multipart('admin/users_group_update' .'/'. $this->uri->segment(3), $data);?>
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="pull-left" style="padding-top: 7.5px"><h1 class="panel-title"><?php echo $title;?></h1></div>
<div class="pull-right">
Cancel
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
<div class="panel-body">
<?php echo validation_errors('<div class="alert alert-warning text-center">', '</div>'); ?>
<div class="form-group">
<?php
$data = array(
'class' => 'col-sm-2'
);
echo form_label('User Group Name', 'name', $data)
;?>
<div class="col-sm-10">
<?php
$data = array(
'id' => 'name',
'name' => 'name',
'class' => 'form-control',
'value' => set_value('name')
);
echo form_input($data)
;?>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Controller Name</td>
<td>Access</td>
<td>Modify</td>
</tr>
</thead>
<tbody>
<?php if ($controller_files) { ?>
<?php foreach ($controller_files as $controllers) { ?>
<tr>
<td>
<div class="clearfix">
<div class="pull-left">
<?php echo $controllers['name']; ?>
</div>
<div class="pull-right">
<?php if ($controllers['installed']) { ?>
<span class="label label-success">Installed</span>
<span class="label label-danger"><a style="color: #FFF; text-decoration: none;" href="<?php echo $controllers['edit'];?>">Edit Individual Controller</a></span>
<?php } else { ?>
<span class="label label-primary">Not Installed</span>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
<div class="panel-footer">
</div>
</div><!-- Panel End -->
<?php echo form_close();?>
</div><!-- # Page Inner End -->
</div><!-- # Page End -->
</div><!-- # Wrapper End -->
<?php echo Modules::run('admin/common/footer/index');?>
Change this line
'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
to
'edit' => site_url('admin/users_group_controller_update' .'/'. $this->getId($controller))
With in my files variable I had to use the db function to get it to work. No errors show now all fixed.
<?php
class Users_group_update extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user_group');
}
public function index() {
$data['title'] = "Users Group Update";
$controller_files = $this->getInstalled($this->uri->segment(3));
$data['controller_files'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
if ($files) {
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
$do_not_list = array(
'customer_total',
'dashboard',
'footer',
'header',
'login',
'logout',
'menu',
'online',
'permission',
'register',
'user_total'
);
if (!in_array($controller, $do_not_list)) {
$this->db->where('name', $this->uri->segment(3));
$this->db->where('controller', $controller);
$query = $this->db->get($this->db->dbprefix . 'user_group');
if ($query->num_rows()) {
$row = $query->row();
$data['controller_files'][] = array(
'name' => $controller,
'installed' => in_array($controller, $controller_files),
'edit' => site_url('admin/users_group_controller_update' .'/'. $row->user_group_id)
);
}
}
}
}
$this->load->view('template/user/users_group_form_update', $data);
}
public function getInstalled($name) {
$controller_data = array();
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $name);
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$controller_data[] = $result['controller'];
}
return $controller_data;
}
}

Dynamic User Profile management in yii?

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;
}
}
}

Simple File Upload for FuelPHP

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);
}

Categories