Hew I wrote common bootstrap css for form fields.But is applying to hidden fields also.How do I restrict for hidden fields in cakephp 3.x bootstrap.
$myTemplates = [
//'nestingLabel' => '<label{{attrs}}>{{text}}</label>{{input}}{{hidden}}',
'inputContainer' => '<div class="form-group order-status">{{content}}</div>',
'checkboxContainer' => '<div class="checkbox">{{content}}</div>',
'label' => '<label class="col-sm-2">{{text}}</label>',
'input' => '<div class="col-md-3"><input type="{{type}}" name="{{name}}" class="form-control" {{attrs}} /></div>',
'select' => '<div class="col-md-3"><select name="{{name}}"{{attrs}} class="form-control">{{content}}</select></div>',
'textarea'=> '<div class="col-md-8"><textarea name="{{name}}" {{attrs}} class="form-control"></textarea></div>',
];
$this->Form->templates($myTemplates);?>
<fieldset>
<legend><?php echo __('{0} Promotion', $edit ? 'Edit' : 'Add'); ?></legend>
<?php
if($edit) {
echo $this->Form->hidden('id');
echo $this->Form->input('active', array('type' => 'checkbox','div'=>false));
} else {
echo $this->Form->input('active', array('type' => 'checkbox','checked' => true));
}
echo $this->Form->input('name');
echo $this->Form->input('description');
if($edit) {
echo $this->Form->input('promotion_type', array('type' => 'select', 'options' => Configure::read('Sidecart.ModelOptions.Promotion.promotion_types'), 'empty' => '-- Select One --', 'disabled' => true));
echo $this->Form->hidden('promotion_type');
} else {
echo $this->Form->input('promotion_type', array('type' => 'select', 'options' => Configure::read('Sidecart.ModelOptions.Promotion.promotion_types'), 'empty' => '-- Select One --'));
}
?>
In CakePHP 3.0, you can do this with Widgets.
Create src\View\Widget\HiddenWidget.php:
<?php
namespace App\View\Widget;
use Cake\View\Widget\BasicWidget;
use Cake\View\Form\ContextInterface;
use Cake\View\Widget\WidgetInterface;
class HiddenWidget extends BasicWidget implements WidgetInterface {
public function render(array $data, ContextInterface $context) {
$data += [
'name' => '',
];
return $this->_templates->format('hidden' /* <-- Define the template name */, [
'name' => $data['name'],
'attrs' => $this->_templates->formatAttributes($data, ['name'])
]);
}
}
Then in a view file:
<?php
$templates = [ // Define your templates
'hidden' => '<input type="hidden" name="{{name}}"{{attrs}}/>',
'input' => '<div class="col-md-3">' .
'<input type="{{type}}" name="{{name}}" class="form-control" {{attrs}}/>' .
'</div>'
];
$this->Form->templates($templates); // Update the templates in FormHelper
$this->Form->addWidget('hidden', ['Hidden']); // Add the HiddenWidget to FormHelper
echo $this->Form->hidden('id'); // Renders with the 'hidden' template
echo $this->Form->input('name'); // Renders with the 'input' template
Conversely, you may want to do the opposite and create BsFormControlWidget(s) instead. This way, the input fields (hidden and visible) keep their "out-of-the-box" functionality. Your custom implementation would sit alongside -Cake, in general, seems to prefer being built "on-top-of" rather than morphed. Plus your widgets would now be more easily reusable in other projects.
Related
so I have a form that contains a hidden input.
<?= $this->Form->create(null, [ 'class' => '', 'templates' => 'Inspinia.form_basic']) ?>
<?php
echo $this->Form->control('name');
echo $this->Form->control('description', ['type' => 'text']);
echo $this->Form->control('chart_type', [ 'options' => $this->App->availableCharts() ] );
echo $this->Form->control('frequency', [ 'options' => ['monthly' => 'Monthly','quarterly'=>'Quarterly','snapshot' =>'Snapshot','monthly/quarterly' => 'Monthly/Quarterly'] ] );
echo $this->Form->control('public', [ 'options' => ['1' => 'Public','0' => 'Private'] ] );
// $this->Form->unlockField('deleted');
echo $this->Form->hidden('deleted',['value' => 0]);
?>
<?= $this->Form->button(__('Save'), ['class' => 'btn btn-sm btn-primary pull-right m-t-n-xs']) ?>
<?= $this->Form->end() ?>
Whenever I try to submit the form, it throws me this error
Missing field 'deleted' in POST data
I know I can bypass this by just doing
$this->Form->unlockField('deleted');
but I don't want to bypass the security component in Cakephp, so is there any other way I can get CakePhp to allow me to submit this hidden field?
this is my controller nothing too much but here just in case you guys are wondering
public function test() {
if ($this->request->is('post')) {
debug($this->request->data);
}
}
It should like below
<?php
echo $this->Form->input('nameoffield',array('type'=>'hidden'));
?>
or passing a hidden value
<?php
$hidden_value = 0;
echo $this->Form->input('nameoffield',array('type'=>'hidden','value' => $hidden_value));
?>
My zend framework 2 project concerns an online restaurant Menu and I am trying to make a form to add Pizzas to database. But something is wrong with my code. The form won't show up, instead this error shows up:
No element by the name of [pizza_name] found in form
Please help me to find what's wrong with my code.
Here are my files:
addPizzaForm.php:
<?php
namespace Pizza\Form;
use Zend\Form\Form;
use Pizza\Form\AddPizzaForm;
use Pizza\Model\Pizza;
class AddPizzaForm extends Form
{
public function construct() {
parent:: construct('addpizzaform');
$this->add(array(
'name' => 'pizza_name',
'type' => 'text',
'options' => array(label => 'Pizza name')));
$this->add(array(
'name' => 'ingredients',
'type' => 'textarea',
'options' => array(label => 'Ingredients')));
$this->add(array(
'name' => 'small_price',
'type' => 'text',
'options' => array(label => 'Small price')));
$this->add(array(
'name' => 'big_price',
'type' => 'text',
'options' => array(label => 'Big price')));
$this->add(array(
'name' => 'family_price',
'type' => 'text',
'options' => array(label => 'Family price')));
$this->add(array(
'name' => 'party_price',
'type' => 'text',
'options' => array(label => 'Party price')));
$this->add(array(
'name' => 'add_pizza',
'type' => 'submit',
'attributes' => array(
'value' => 'Add New Pizza',
'id' => 'submitbutton')));
}
}
add.phtml view:
<?php
echo $this->headTitle('Add new Pizza');
?>
<div class="row">
<div class="col-md-8"> <h1> Add new Pizza </h1>
</div>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('pizza',array('action'=>'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('pizza_name')) . "</br>";
echo $this->formRow($form->get('ingredients')) . "</br>";
echo $this->formRow($form->get('small_price')) . "</br>";
echo $this->formRow($form->get('big_price')) . "</br>";
echo $this->formRow($form->get('family_price')) . "</br>";
echo $this->formRow($form->get('party_price')) . "</br>";
echo $this->formRow($form->get('add_pizza')) . "</br>";
echo $this->form()->closeTag();
?>
PizzaController.php:
<?php
namespace Pizza\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Pizza\Form\AddPizzaForm;
use Pizza\Model\Pizza;
class PizzaController extends AbstractActionController {
protected $pizzaTable;
public function addAction()
{
$add_form = new AddPizzaForm();
$request = $this->getRequest();
if($request->isPost())
{
$pizza = new Pizza();
$add_form->setInputFilter($pizza->getInputFilter());
$add_form->setData($request->getPost());
if($form->isValid())
{
$pizza->exchangeArray($form->getData());
$this->getPizzaTable()->save($pizza);
}
return $this->redirect()->toRoute('pizza');
}
return array('form' => $add_form);
}
public function getPizzaTable()
{
if( !$this->pizzaTable)
{
$sm = $this->getServiceLocator();
$this->pizzaTable = $sm->get('Pizza\Model\PizzaTable');
}
return $this->pizzaTable;
}
}
Welcome to stackoverflow!
You're getting that strange errors because there are FOUR important details that needs attention.
A - Your construct() method in AddPizzaForm has wrong name and signature. You have to rename construct to __construct change contents something like below:
class AddPizzaForm extends Form
{
public function __construct($name = null, $options = array() )
{
$formName = is_null($name) ? 'addpizza-form' : $name;
parent::__construct($formName, $options);
}
}
B - Create an init() method in your form and add your form elements inside that. This detail is clearly stated in official documentation:
If you are creating your form class by extending Zend\Form\Form, you
must not add the custom element in the __construct but rather in the init() method.
So, in your case:
class AddPizzaForm extends Form
{
// constructor etc..
public function init()
{
$this->add(array(
'name' => 'pizza_name',
'type' => 'text',
'options' => array(label => 'Pizza name')
)
);
// ... add other for elements ...
}
}
C. Finally, in your controller, you're trying to instantiate your form manually:
$add_form = new AddPizzaForm();
This is also bad practice. You need to get your AddPizzaForm instance from ServiceManager. This detail also stated in documentation:
You must not directly instantiate your form class, but rather get an
instance of it through the Zend\Form\FormElementManager.
To do that, introduce your AddPizzaForm in module.config.php like below:
'form_elements' => array(
'invokables' => array(
'add-pizza-form' => 'Pizza\Form\AddPizzaForm',
)
)
And grab it in your controller like this:
$add_form = $this->getServiceLocator()->get('FormElementManager')->get('add-pizza-form');
D - The last thing is; please read most of the documentation first before making some experiments. Reading documentation is most important step to getting better in any language or framework.
Hope it helps. Happy coding!
Hello i created a separate search form having input box and button.
in my model i want to search products by category wise...
but problem is that when input box is empty and clicking on search buttons it displays all entries from the database table..
controller code is-
class AddController extends Controller
{
public function actionAddsearch()
{
$model_form = new Add("search");
$attributes = Yii::app()->getRequest()->getPost("Add");
if(!is_null($attributes))
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
}
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
}
model code--
class Add extends CActiveRecord
{
public function searchAdd()
{
$criteria = new CDbCriteria();
$criteria->compare("addname", $this->category, TRUE, "OR");
$criteria->compare("category", $this->category, TRUE, "OR");
return Add::model()->findAll($criteria);
}
view code- addsearch.php
<div class="search-bar">
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
"action"=>$this->createUrl("add/addsearch"),
'type'=>'search',
)
);
echo $form->textFieldRow($model,'category');
echo "        ";
$this->widget('bootstrap.widgets.TbButton',array(
'buttonType'=>'submit',
'type'=>'success',
'size'=>'large',
'label'=>'Search For Products ',
));
$this->endWidget();
?>
</div>
searchResults.php
<?php
echo "<h4>Results for Your Search</h4>";
foreach($models as $model):
$this->beginWidget('bootstrap.widgets.TbDetailView',array(
'type'=>'bordered condensed',
'data' => array(
'Shop Name' =>CHtml::link(CHtml::encode($model->addname),array('add/view','id'=> $model->addid)),
'Category' => $model->category
),
'attributes' => array(array('name' => 'Shop Name', 'label' => 'Name of Shop','value'=>CHtml::link(CHtml::encode($model->addname),
array('add/view','id'=>$model->addid)),'type'=>'raw'),
array('name' => 'Category', 'label' => 'Category of Shop'),
),
)
);
echo "<br><hr><br>";
$this->endWidget();
endforeach;
?>
what is wrong in the code??
I want to display no any product when text box is empty..
thanks in advance
change this
if(!is_null($attributes))
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
}
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
To
if($attributes)
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
}
1) Is the 'caterory' attribute safe on search scenario ? (in rules)
2) category is an attribute of the table schema ?
I want to make a validation form in cakephp my code form is:
view
<div class="well">
<?php
echo $this->Form->create(false);
echo $this->Form->input('name', array('label' => 'name '));
echo $this->Form->input('PHONE_NUMBER', array('label' => 'PHONE_NUMBER '));
echo $this->Form->input('EMAIL', array('label' => 'EMAIL '));
echo $this->Form->input('ISSUE', array('label' => 'ISSUE '));
echo $this->Form->input('IP', array('label' => 'IP '));
echo $this->Form->submit('Send.');
?>
Controller
<?php
class ContactController extends AppController {
public function index() {
if (empty($_POST) === FALSE) {
$message = '';
$message .=$_POST['data']['EMAIL'] . ' <br/>';
$message .=$_POST['data']['name'] . ' <br/>';
$message .=$_POST['data']['PHONE_NUMBER'] . ' <br/>';
$message .=$_POST['data']['ISSUE'] . ' <br/>';
$message .=$_SERVER['REMOTE_ADDR'] . ' <br/>';
mail('mohmed#lcegy.com', 'Support From Website ', $message);
$this->Session->setFlash("Thanks , an email just sent .");
}
}
}
My question is how to implement validation in this form and how to get the IP address of the visitor?
You may want to update your index() function to look something similar to this: I think it's more of the cakePHP convention.
public function index() {
if ($this->request->is('post')) {
$message = '';
$message = $this->request->data['EMAIL'];
...
}
}
For validation, you can add that to your model. You could do something similar:
public $validate = array(
'EMAIL' => 'email',
'name' => array(
'rule' => 'alphaNumeric',
'required' => true
)
);
For more validation, you can look at the documentation: http://book.cakephp.org/2.0/en/models/data-validation.html
You can use $_SERVER['REMOTE_ADDR'] to get the client's IP Address.
You Can Do Validation From Your Model by setting Rules as follows
public $validate =
array(
'Email' => array
(
'rule' => 'notempty'
),
);
Best way to do it by model as above given answers but you can also do it at view page by simply adding attributes "require" and define proper types like emails, numbers. eg. in your form:
<?php
echo $this->Form->create(false);
echo $this->Form->input('name', array('label' => 'name ', 'required' => true));
echo $this->Form->input('PHONE_NUMBER', array('label' => 'PHONE_NUMBER ', 'required' => true,'type'=>'number'));
echo $this->Form->input('EMAIL', array('label' => 'EMAIL ', 'required' => true, 'type' => 'email'));
echo $this->Form->input('ISSUE', array('label' => 'ISSUE ', 'required' => true));
echo $this->Form->input('IP', array('label' => 'IP ', 'required' => true));
echo $this->Form->submit('Send.');
?>
i want to validate 2 date input in codeigniter, with the conditions, if the end date is greater than the start date, will appear warning [javascript warning or something] or data can't be input
my form like this,
<h1><?php echo $title; ?></h1>
<form action="<?= base_url(); ?>index.php/admin/kalender/buat" method="post" enctype="multipart/form-data" name="form" id="form">
<?php
echo "<p><label for='IDKategori'>Tingkatan Pimpinan :</label><br/>";
echo form_dropdown('IDKategori', $kategori) . "</p>";
echo "<label for='ptitle'>Kegiatan / Lokasi :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'judul', 'id' => 'ptitle', 'size' => 80);
echo form_input($data);
echo "<p><label for='long'>Uraian Kegiatan / Keterangan / Catatan :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'konten', 'rows' => '13', 'cols' => '60', 'style' => 'width: 60%');
echo form_textarea($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Mulai :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalMulai', 'id' => 'basic_example_1');
echo form_input($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Akhir :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalAkhir', 'id' => 'basic_example_2');
echo form_input($data) . "</p>";
echo form_submit('submit', 'Tambah Even');
?>
<input type="button" value="Kembali" onClick="javascript: history.go(-1)" />
how to validate in form "Waktu Akhir & Waktu Mulai" ?
Try this. It is by using CI validation library.
It uses callback type of validation.
Put this in if(isset($_POST['submit_button_name'])) {} section.
First, load validation array,
$validation = array(
array('field' => 'startDate', 'label' => 'StartDate', 'rules' => 'required|callback_compareDate'),
array('field' => 'endDate', 'label' => 'endDate', 'rules' => 'required|callback_compareDate'),
);
Then load CI validation library as,
$this->form_validation->set_rules($validation);
$this->form_validation->set_message('required', '%s is required.');
This is the called back function.
function compareDate() {
$startDate = strtotime($_POST['startDate']);
$endDate = strtotime($_POST['endDate']);
if ($endDate >= $startDate)
return True;
else {
$this->form_validation->set_message('compareDate', '%s should be greater than Contract Start Date.');
return False;
}
}
The "required" validation makes the fields mandatory to be filled with something.
The callback function, in this case, compares the dates, and further processes the form if start date is less than from date OR flags error otherwise.
Meanwhile, if you want in Jquery you can use this.
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate > endDate){
alert("Start Date should be less than End Date");
return false;
}
This is working code
$params['toDate'] = $this->input->post('toDate', TRUE);
$params['fromDate'] = $this->input->post('fromDate', TRUE);$this->load->model('your_model');
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$startDate = strtotime($params['fromDate']);
$endDate = strtotime($params['toDate']);
if ($endDate >= $startDate):
$this->form_validation->set_rules('fromDate', 'From Date', 'required|trim');
$this->form_validation->set_rules('branchCode', 'Branch Code', 'required|trim');
else:
$json = array(
"success" => false,
"msg" => "Start date must be greater than end date"
);
echo json_encode($json);
die();
endif;