Codeigniter: insert form_input into sql table - php

I'm trying to create a system of posts and custom fields. Ex: I create the post type "Product" and then I associate it some fields: "Name", "Image", "Price"...
When I create one of this fields I save into my db an input field, for example for Name I will insert something like this:
$data = array(
'name' => $field_key,
'id' => $field_key,
'class' => 'form-control '.$type->type_key,
'type' => $type->type_key,
'data-input-type' => $type->type_key
);
return form_input($data);
Then when I go to create my first post "Product" I want to populate a form with my custom fields.
<form method="post" action="<?php echo site_url('admin/posts/manage').'/'.$post_id; ?>">
<?php
foreach ($post_fields as $field) {
?>
<div class="form-group">
<label>
<?php
echo $field->name;
?>
</label>
<?php
// Here the field input
echo $field->meta_value;
?>
</div>
<?php
}
?>
<?php if(isset($post)){ echo $post->name;}else{echo set_value('name');} ?>
<div class="form-group">
<input type="submit" value="Save" name="save">
</div>
</form>
There's no problem since I have to create a new one. But when I have to edit my post I don't know how to load field's value for that single post, because in my form_input $data I can't put something like
$value = (isset($post)) ? $post->name : set_value($field_key);
and in the $data array
'value' => $value
Somebody have an idea on what I can do?
Thank you and sorry for my elementary english.

SOLVED. I create a model which load the correct input type. I pass post values by the controller to this model to populate input values correctly, if the action required is "edit".

Related

Cakephp 3 Search Function

got a question about cakephp3 search function, is it possible to search among two tables/Controllers in a search form?
this is the codes, am trying to search from categories name and also products name, their relationship is products has category id
this is the code from the Controller
$c = $this->request->getQuery('c');
if(!empty($c)) {
$this->loadModel('Categories');
$category = TableRegistry::get('Categories');
$query = $this->Products->find()->contain(['Categories'=>['Products']])
->where(['Categories.name LIKE' => '%' . $c. '%']);
}
$this->set(compact('c','query'));
$key = $this->request->getQuery('key');
if(!empty($key)) {
$products->where(['Products.name LIKE ' => '%'.$key.'%']);
}
$this->set(compact('key'));
this is from the HTML side, where i name="c", it only search for c and not key,
<?php echo $this->Form->create(null, ['type' => 'get', 'valueSources' =>
'query'); ?>
<?php echo $this->Form->control('search', ['type' => 'hidden']); ?>
<input type="text" class="form-control" name="c" placeholder="Search...">
<span class="input-group-append">
<button type="submit">
<?php echo $this->Form->end(); ?>
is there a method to combine both search in a form?
thank you for your helps

Codeigniter Form post controller advice

would like some advice/help on how to connect form controller to post form method in my CI site. I want to data submitted from one viewer to another. Thank you for the help!!
Here is the controller Im using (Form.php), took if from another site:
Form.php
<?php
class Form extends CI_Controller {
public function __construct() {
parent::__construct();
}
// Show form in view page i.e view_page.php
public function form_show() {
$this->load->view("addEdit");
}
// When user submit data on view page, Then this function store data in array.
public function data_submitted() {
$data = array(
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
);
// Show submitted data on view page again.
$this->load->view("profile", $data);
}
}
?>
Its to connect to this code:
addEdit.php
<form method="post" action="postAction.php" enctype="multipart/form-data">
<div class="form-group">
<label>Image</label>
<?php if(!empty($imgData['file_name'])){ ?>
<img src="uploads/images/<?php echo $imgData['file_name']; ?>">
<?php } ?>
<input type="file" name="image" class="form-control" >
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" class="form-control" placeholder="Enter title" value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" >
</div>
Back
<input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">
<input type="submit" name="imgSubmit" class="btn btn-success" value="SUBMIT">
</form>
When I first tried to make it work I got this error:
404 Page Not Found
The page you requested was not found.
http://culturedkink.com/index.php/register/postAction.php(the url)
postAction.php is the form Im trying to get the data to work from
The end result is to have info submitted from addEdit.php be seen on profile.php with the help of postAction.php
make routes for it first.
config/routes.php
$route['add'] = 'Controller_name/data_submitted';
$route['edit/(:any)'] = 'Controller_name/data_submitted/$1';
where is your add/edit button put this there
for add
Add New
for edit button
$row['id'] is an example i m giving. you can get data by name and id..whatever you want.
Update
//controller
public function data_submitted($id=0) {
$data=array();
$data['dataDetails']=$this->get_profile_data_by_id($id);
$data['view'] = 'folder_name/addEdit';
if ($id > 0) {
$profileArray = [
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
];
if ($this->User_model->editById($id, $profileArray)) {
$id = $id;
}
}
else{
$profileArray = [
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
];
if ($this->User_model->add($id, $profileArray)) {
$id = $id;
}
}
$this->load->view("profile", $data);
}
form view page
<?php echo isset($dataDetails) ? "Update" : "Add"; ?>
First check your form method and action. Your action does not exist. First check how CI works with form. The action should have a method declared in a controller. The url looks like this,
When you submit the form the data will be submitted in this method. Whatever you need to do with this form data you can do that in this method.

How to display seleced option in yii dropdown?

I created a drop-down to select the category for search. When I search the product for example I search Shoes for MEN, when the view page loaded the item resets to default
I want the category to remain what I selected
<form action="<?php echo Yii::app()->baseUrl; ?>/search" method="GET" class="form-inline form-section-2 row fadeInDown animated">
<div class="col-sm-5 form-group">
<input type="text" name="loc" class="form-control" id="loc" value="<?php echo $locationdet ; ?>" placeholder="Enter Your Keyword">
</div>
<div class="col-sm-4 form-group" >
<select name="cat" class="form-control selectpicker">
<option>Select Category</option>
<option value = '0'>Men</option>
<option value = '1'>Women</option>
</select>
</div>
<div class="col-sm-3 form-group">
<button type="submit" class="btn btn-default btn-new">Search Products</button>
</div>
</form>
Try this:
<option value = '0' <?php if(isset($_GET['cat']) && $_GET['cat'] == '0') echo "selected" ?>>Men</option>
<option value = '1' <?php if(isset($_GET['cat']) && $_GET['cat'] == '1') echo "selected" ?>>Women</option>
use
echo CHtml::dropDownList('cat',isset( $_REQUEST['cat'] ) ? $_REQUEST['cat'] : NULL, array('0'=>'Men', '1'=>'Women'),
array('empty'=>'Select Category', 'class' => 'form-control selectpicker'));
to achieve yii style,
cheers
You will have to pass the selected option via the controller back to the view.
In the controller you will need something like this:
$this->render('viewName', array('name' => 'valueOfTheList'))
Then in the view you can use
<option value = '0' <?php if($name == '0') echo "selected" ?>>Men</option>
<option value = '1' <?php if($name == '1') echo "selected" ?>>Women</option>
However. Since you are using Yii. I would advise you to look at CHTML::dropDownList(). Then you could do something like
<?php echo CHtml::dropDownList('name', $select,
array('M' => 'Male', 'F' => 'Female'));
Which is really a more Yii way to approach these kind of things.
Yii way to implement this functionality.
You can keep the form state by setting the user input value to Model properties. For this, you can use CFormModel to implement, same like YII's default login page. Below is a sample example.
Create a form model for your search (SearchForm.php) and place this inside models folder.
class SearchForm extends CFormModel
{
public $search_key;
public $search_cat;
public function rules()
{
return array(
array('search_key,search_cat', 'required'),
);
}
}
Assume i am using SiteController. I want to show this search form in my index page. When i submit the form it will submitted to search action
class SiteController extends Controller
{
public function actionIndex()
{
$searchModel=new SearchForm();
$searchModel->search_key;
$searchModel->search_cat;
$this->render('index',array('searchModel'=>$searchModel));
}
public function actionSearch()
{
$searchModel=new SearchForm();
if($_POST['SearchForm'])
{
$searchModel->attributes=$_POST['SearchForm'];
}
$this->render('search',array('searchModel'=>$searchModel));
}
}
$searchModel->attributes=$_POST['SearchForm']; That is i am resetting the user inputs to model.So, in your view the form will appear with user input values.
Call this Form in views
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'search-form',
'enableClientValidation' => true,
'action'=>array('default/search'), //Submiting my form to Search action
));
?>
<?php echo $form->textField($searchModel, 'search_key'); ?>
<?php
$htmlOptions = array('size' => '1', 'prompt' => 'Select');
$list = array('0' => 'Men', '1' => 'Women'); // You can load your Categories from the Database table/Model.
echo $form->dropDownList($searchModel, 'search_cat', $list, $htmlOptions);
?>
<?php echo CHtml::submitButton('Search'); ?>
<?php $this->endWidget(); ?>
Hope, This will help you for your better practice.

Render Radio Element in Zend Forms

I have defined a form using Zend\Form. In that, there is a radio button.
$this->add(array(
'name' => 'nationality_radio',
'type' => 'Radio',
'options' => array(
'value_options' => array(
'local' => 'Local',
'expatriate' => 'Expatriate',
),
)
));
Its value is not directly binded with database column. But it should populate correct value taken form DB and save user input back. (eg - if value of table column nationality is local it should select local in radio button)
When rendered it should display as..
On form load, it will a select option considering column nationality. It will contain value either local or expatriate
<?php
if ($candidate->nationality == 'local'){
$local = 'checked';
} else if ($candidate->nationality == 'local'){
$expatriate = 'checked';
}
?>
In plain HTML i can do it as below,
<div class="profile_item list-group-item">
<span class="item_title">Local: </span>
<span class="item_content"><input type="radio" name="nationality" value="local" <?php echo $local ?>></span><br>
<span class="item_title">Expatriate: </span>
<span class="item_content"><input type="radio" name="nationality" value="expatriate" <?php echo $expatriate ?>></span>
</div>
But since Zend form rendered using <?php echo $this->formRow($form->get('nationality_radio')); ?> I couldn't do it. It just displayed as below.
How can i achieve my requirement ?
For set the value, within controller method:
$form = new YourFormClass();
//are you using fieldsets? let's say no...
//if accepted value for $candidate->nationality could be only 'local' and 'expatriate',
//check the scope with your defined value_options or use an if
$form->get('nationality_radio')->setValue($candidate->nationality);
On your view use formRadio helper:
<?php echo $this->formRadio($form->get('nationality_radio'),\Zend\Form\View\Helper\FormRadio::LABEL_PREPEND);?>
Check out documentation at: http://framework.zend.com/manual/2.2/en/modules/zend.form.elements.html#radio
or check classes:
\Zend\Form\View\Helper\FormRadio
and
\Zend\Form\View\Helper\FormMultiCheckbox
Accepted values for $labelPosition are:
const LABEL_APPEND = 'append';
const LABEL_PREPEND = 'prepend';
Try this
<?php
if ($candidate->nationality == 'local'){
$LocalChecked="checked";
}
else {
$expatriateChecked ="checked";
}
?>
<div class="profile_item list-group-item">
<span class="item_title">Local: </span>
<span class="item_content"><input type="radio" name="nationality" value="local" <?php echo $LocalChecked ?>></span><br>
<span class="item_title">Expatriate: </span>
<span class="item_content"><input type="radio" name="nationality" value="expatriate" <?php echo $expatriateChecked ?>></span>
</div>

Behaviors with forms in yii

I have a Yii behavior, that adds some custom fields with condition
_form.php
$form->attachbehavior('users', new DirectoriesBehavior);
// return part of form
echo $form->getDirectory(array('sysName' => 'users', 'useDefaultValue' => true));
// Other form parts (default for yii)
echo $form->labelEx($model, 'name');
DirectoriesBehavior::getDirectory() build HTML form part with <select> or <input> etc. fields.
But how can I send name/id of the form to my behavior?
After rendering it looks like
<form method="" id="myForm">
<!--BEHAVIORS CONTENT-->
<select>
<option value="UserId">UserName</option>
</select>
<!--Default fields of form-->
<input type="text" name="myForm[exampleField]" />
</form>
And my behaviors content should to looks like
<select name="myForm[users]">
<option>etc</option>
</select>
I resolve this problem:
We can sent $model in _form.php
$form->getDirectory(array('model' => $model));
in DirectoriesBehavior.php
public function getDirectory(array $data)
{
$this->inputName = get_class($data['model']);
}
Also ( for scripts that will be work with this form we can to send ID of the form )
_form.php
$form->id;

Categories