I want to force the Zend form into Twitter Bootstrap style. I currently iterate through the form fields and write the form info into my bootstrap div construction.
I saw in Zend Framework 1(!) that there is a way to do this within a decorator. But for some reason the doc for version 2 doesn't cover this point...
I'd like to do something like this:
protected $_format = '<label for="%s">%s</label>'
. '<input id="%s" name="%s" type="text" value="%s"/>';
public function render($content)
{
$element = $this->getElement();
$name = htmlentities($element->getFullyQualifiedName());
$label = htmlentities($element->getLabel());
$id = htmlentities($element->getId());
$value = htmlentities($element->getValue());
$markup = sprintf($this->_format, $name, $label, $id, $name, $value);
return $markup;
}
Any ideas?
I'm using partials now. I'm iterating over the attributes, build a few exceptions for eg CSRF and Submit... This works pretty smooth:
View
echo $this->partial('partial/form-partial', array(
'form' => $this->form,
'url' => $this->url('whatever', array('action' => 'add')))); ?>
Partial
<?php
$form = $this->form;
$form->setAttribute ( 'action', $this->url () );
$form->prepare ();
echo $this->form ()->openTag ( $form );
foreach ( $form as $element ) :
?>
<div
class="control-group <?php if($this->formElementErrors($element)) echo "error" ?>">
<label class="control-label"><?php echo $element->getLabel() ?></label>
<div class="controls">
<?php echo $this->formElement ( $element );
if ($this->formElementErrors ( $element ))
?>
<span class="help-inline"><?php echo $this->formElementErrors($element) ?></span>
</div>
</div>
<?php
endforeach;
echo $this->form ()->closeTag ( $form );
?>
The exceptions are left out for clearity's sake...
I did it the way #Rufinus mentioned. See this Tutorial on how to create View Helpers in ZF2 http://blog.evan.pro/creating-a-simple-view-helper-in-zend-framework-2
In my case I simply wanted to wrap form elements with list items so I extended the original ZF2 View Helpers and let them do the rendering of the elements. I Just wrapped what they return:
View Helper FormCollection.php
<?php
// ./src/Application/View/Helper/FormCollection.php
namespace Application\View\Helper;
use Zend\Form\ElementInterface;
use Zend\Form\View\Helper\FormCollection as BaseFormCollection;
class FormCollection extends BaseFormCollection {
public function render(ElementInterface $element) {
return '<ul>'.parent::render($element).'</ul>';
}
}
View Helper FormElement.php
<?php
// ./src/Application/View/Helper/FormElement.php
namespace Application\View\Helper;
use Zend\Form\ElementInterface;
use Zend\Form\View\Helper\FormElement as BaseFormElement;
class FormElement extends BaseFormElement {
public function render(ElementInterface $element) {
if ($element->getOption('required')) {
$req = 'required';
}
$type = $element->getAttribute('type');
$name = $element->getAttribute('name');
return sprintf('<li class="%s %s %s">%s</li>', $name, $req, $type, parent::render($element));
}
}
while my view looks like this and didn't need to be modified for the changes to take effect.
<?php
$form = $this->form;
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formCollection($form);
echo $this->form()->closeTag($form);
worked like a charm.
I tried Ron's Partial method, the result would like this which not Bootstrap 3 intended.
<form id="tea" name="tea" method="POST" action="/tea/add">
...
<div class="form-group">
<label class="control-label">Brand</label>
<div class="form-control">
<input type="text" value="" name="brand">
</div>
...
We know, in order to use bootstrap 3 predefined Form style, we need to define style to input element: form-control, rather than its wrapping element.
My Partial way is as following.
echo $this->form()->openTag($form);
foreach ($form as $element) :?>
<div class="form-group">
<?php
if ($element->getOption('required')) { $req = 'required'; }
$type = $element->getAttribute('type');
$name = $element->getAttribute('name');
$label = $element->getLabel();
?>
<?php if ($name == 'id') { ?>
<div class="hidden"><?php echo $this->formElement($element); ?></div>
<?php } else if ($name == 'submit') { ?>
<input class='btn' name='submit' type='submit' value='Add'>
<?php } else if ($label != '') { ?>
<label class="control-label"><?php echo $label ?></label>
<input class='form-control' name='<?php echo $name ?>' type='<?php echo $type ?>'>
<?php } ?>
</div>
<?php
endforeach;
echo $this->form()->closeTag();
Well, we could get the result.
<form id="tea" name="tea" method="POST" action="/tea/add">
...
<div class="form-group">
<label class="control-label">Brand</label>
<input class="form-control" type="text" name="brand">
</div>
...
How to attach custom styles into zf2 forms has mentioned : to add class attribute to the Form element.
class TeaForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('tea');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'brand',
'type' => 'Text',
'options' => array(
'label' => 'Brand',
),
/** **define class attribute** **/
'attributes' => array(
'class' => 'form-control',
),
));
....
It looks quite simple, but, the problem is the input element would be wrapped into the label element, which still not what Bootstrap 3 intended.
<form id="tea" role="form" name="tea" method="POST" action="/tea/add">
<input type="hidden" value="" name="id">
<label>
<span>Name</span>
<input class="form-control" type="text" value="" name="name">
</label>
...
In my opinion, the Partial method is still one flexible and light choice. Tea Box is one ZF2 practice, you could find all above mentioned code and description from Gibhub
This will make the code easier.
http://php.net/manual/en/function.echo.php
<?php
$form->prepare();
echo
$this->form()->openTag($form),
$this->formCollection($form),
$this->form()->closeTag($form);
Related
i am new using codigniter. i am trying to display images from the mysql database by sending them to the database using a create page where you can type in a title, some info and select an image, everything displays after creating a project except for the image. once i open phpmyadmin it shows that there is data for the image but it looks like it's only MetaData and not the actual image itself. i have been stuck on this for a couple of days now so i hope you guys could help me out!
create function in The Controller (edited):
public function create(){
$model = new ProjectModel();
$file = $this->request->getFile('image');
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'info' => 'required',
'image' => 'uploaded[image]',
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'info' => $this->request->getPost('info'),
$tempfile = $file->getTempName(),
$imgdata = file_get_contents($tempfile),
]);
var_dump($imgdata);
#echo view('project/success');
}
else
{
echo view('site/create');
}
}
My Model
namespace App\Models;
use CodeIgniter\Model;
class ProjectModel extends Model
{
protected $table = 'projects';
protected $allowedFields = ['title', 'slug', 'info', 'image'];
public function getProjects($slug = false)
{
if ($slug === false)
{
return $this->findAll();
}
return $this->asArray()
->where(['slug' => $slug])
->first();
}
}
this is the file that creates a div element once you press the create button
<?php if (! empty($projects) && is_array($projects)) : ?>
<?php foreach ($projects as $project_item): ?>
<div class="project-box" href="/projects/<?= esc($project_item['slug'], 'url') ?>">
<?php echo '<img class="project-image" src="data:image/jpeg;base64,'.base64_encode($project_item['image']).'" alt="image" ">'?>
<p class="project-name"><?=esc($project_item['title'])?></p>
<div class="bottom-border">
<p class="project-creator"><i class="far fa-user-circle"></i> <?=esc($project_item['creator'])?></p>
<div class="statistics">
<p class="project-likes"><i class="fas fa-heart"></i> <?=esc($project_item['likes'])?></p>
<p class="project-views"><i class="far fa-eye"></i> <?=esc($project_item['views'])?></p>
</div>
</div>
</div>
<?php endforeach; ?>
<?php else : ?>
<h3>No Projects</h3>
<?php endif ?>
this is the create file in which you can create a project
<div class="parent">
<?= \Config\Services::validation()->listErrors() ?>
<form action="/site/create" method="post">
<h1>Create Project</h1>
<?= csrf_field() ?>
<div class="form-group">
<input class="ph-title" type="input" name="title" placeholder="Title" /><br/>
</div>
<div class="grow-wrap">
<textarea class="ph-info" name="info" placeholder="Type in project info"></textarea>
</div>
<!-- <div class="file-input">
<label for="file">
Select file
<p class="file-name"></p>
</label>
</div> -->
<input class="file-btn" type="file" name="image" value=""/><br/>
<input class="create-btn" type="submit" name="submit" value="Create Project"/>
</form>
</div>
What am i doing wrong?
There are a few things wrong here. First off, your form is set for image uploading, but needs the enctype added to the form tag so that your backend PHP can recieve the $_FILES object
<form action="/site/create" method="post" enctype="multipart/form-data">
Remove the value="" from the input...
<input class="file-btn" type="file" name="image" />
Now you're ready to receive a file - see https://codeigniter4.github.io/userguide/libraries/uploaded_files.html
Your validation should be altered
$this->validate([
//... your other validations...
'image' => 'uploaded[image]' // instead of required
]);
If you want to store the image on your server and then record the name of the image in the database to retrieve later:
$imageDirectory="/path/to/where/you/store/images";
$imageName = $file->getRandomName();
$path = $this->request->getFile('image')->store($imageDirectory, $imageName);
// path is now the full path to the image on your server.
if you want to store the image BLOB data instead (like your example):
$tempfile = $file->getTempName();
$imgdata = file_get_contents($tempfile);
Then your insert would look like this...
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'info' => $this->request->getPost('info'),
'image' => $imgdata,
]);
So I'm new to codeigniter and developing a viewing catalogue website. And so far my update function isn't working and I've been at this for 3 hours
so here's my view:
<?php echo validation_errors(); ?>
<?php echo form_open('catalogPages/updateEvent'); ?>
<input type="hidden" name="id" value="<?php echo $events['event_id']; ?>">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" placeholder="Add
Title" value= "<?php echo $events['event_name']; ?>">
</div>
<div class="form-group">
<label>Body</label>
<textarea id="editor1" class="form-control" name="body" placeholder="Add
Body" value = "<?php echo $events['event_desc']; ?>"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
My Model:
public function editEvent()
{
$data = array(
'event_name' => $this->input->post('event_name'),
'event_desc' => $this->input->post('event_desc'),
'event_id' => $this->input->post('event_id')
);
$this->db->where('event_id', $this->input->post('event_id'));
return $this->db->update('events', $data);
}
Controller:
public function editEvent($id = NULL)
{
$this->load->model('event_model');
$data['events'] = $this->event_model->get_event($id);
$this->load->view('adminEventUpdate', $data);
}
public function updateEvent()
{
$this->load->model('event_model');
//$id = $this->input->posts('event_id');
$this->event_model->editEvent();
}
It works but so far when I try to update the data doesn't seem to be updated but rather doesn't change at all.
When this Html form is submitted, the $_POST array has the keys:
'id', 'title', and 'body'.
There are no inputs named 'event_id', 'event_name', 'event_desc'.
The Html input properties 'name' need to change.
im trying to add new post into my db. I have Model, Controller and View created. Actualy im using rest api for this, but now I want to do it with pure php powerd.
But After form validation is nothing. So when I try to post, nothuing happens.
Here is my code.
Model:
// Create
function create($data) {
// Insert data into DB
$this->db->insert('blog', $data);
return $this->db->insert_id();
}
Controller:
public function add() {
if ($this->ion_auth->is_admin()) {
// Validation rules
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
if (($this->form_validation->run() == FALSE)) {
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
if($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
$this->blog_model->create($data);
redirect(base_url().'blog/');
}
}
} else {
redirect('login');
}
}
And at least my view:
<div class="uk-margin-top">
<?php $attributes = array("class" => "uk-panel uk-panel-box uk-form uk-margin-lage-bottom", "id" => "add-form", "method" => "post");
echo form_open("/backend/blog/add", $attributes); ?>
<div class="uk-form-row">
<label class="uk-form-label" for="title">Title</label>
<input id="title" class="uk-width-1-1 uk-form-large title redactor-box" name="title" placeholder="Beitragstitel" type="text"
value="<?php echo set_value('title'); ?>"/>
<span class="uk-text-danger"><?php echo form_error('title'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="teaser">Teaser</label>
<textarea id="teaser" class="uk-width-1-1 uk-form-large teaser redactor-box" name="teaser" data-uk-htmleditor></textarea>
<span class="uk-text-danger"><?php echo form_error('teaser'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="body">Body</label>
<textarea id="full" name="full" rows="4" placeholder="Ihre Nachricht"
value="<?php echo set_value('full'); ?>"></textarea>
<span class="uk-text-danger"><?php echo form_error('full'); ?></span>
</div>
<div class="uk-form-row">
<a class="uk-button uk-button-success" data-action="add-post">Submit</a>
</div>
<?php echo form_close(); ?>
</div>
So my problem is, when I click on my submit button - nothing. Maybe you can show me where my problem is.
Thank you!
For your controller, I think you are missing the form helper and validation library. I have included other comments in the code, but try this:
public function add() {
// you need to load these in:
$this->load->helper('form');
$this->load->library('form_validation');
// I am assuming ion_auth is working, however, I would try this code without
// this conditional statement
if ($this->ion_auth->is_admin()) {
// Validation rules
// Make sure the second parameter is right. I think Titel should be Title.
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
// added a triple === instead of == for stricter type checking
if (($this->form_validation->run() === FALSE)) {
// I am assuming $this->data is a property of your controller class
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
// Check if the form was submitted via $_POST method
if($this->input->post()) {
// I removed your $data array and created it in the model.
// I added a condition here to check if the data was successfully inserted
if ($this->blog_model->create()) {
redirect(base_url().'blog/');
} else {
// output an error message or redirect
}
}
}
} else {
redirect('login');
}
}
For your model, I think you were not passing any data to your model. Try the following for your model:
public function create()
{
// you need to pass an array of data or an object
// the array key corresponds to your db table column
// the array value corresponds to your views input field names
$data = array(
'name' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
// returns true or false
return $this->db->insert('blog', $data);
}
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.
I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.