CakePHP Making a form to be global with validation - php

My application has contacts controller with add action which able to post contacts message to the database table comments. It works fine with its validation.
Now I want to use the add view (The contacts form) as a global form to be rendered in all pages of the application.
I know, to do that, I have to make an element contains the form (or the add view) as follows:
elements/contact.ctp
<div class="panel">
<h4><?php echo __('contact'); ?></h4>
<?php echo $form->create('Contact',array('action'=>'index', 'class' => ''));?>
<?php echo $form->input('name', array('size' => 45, 'class' => 'input-text', 'label' => array( 'text' => __('name',true).'<sup>*</sup>'), 'error' => array('class' => 'error', 'wrap' => 'small')));?>
<?php echo $form->input('email', array('size' => 45, 'class' => 'input-text', 'label' => array('text' => __('email',true).'<sup>*</sup>'), 'error' => array('class' => 'error', 'wrap' => 'small')));?>
<?php echo $form->input('subject', array('type' => 'select', 'options' => array(null => __('choose subject',true), 'g' => __('general', true), 'r' => __('report', true)), 'class' => 'input-text', 'label' => array('text' => __('subject', true).'<sup>*</sup>'),'error' => array('class' => 'error', 'wrap' => 'small'))); ?>
<?php echo $form->input('content', array('class' => 'input-text', 'style' => 'height: 140px', 'title' => __('message', true), 'label' => array('text' => __('message',true).'<sup>*</sup>'), 'error' => array('class' => 'error', 'wrap' => 'small')));?>
<?php //echo $fck->load('Contact.message','Mini'); ?>
<span>
<?php
App::import('Vendor','FoxCaptcha', array('file' => 'Fox_captcha.php'));
$cap = new Fox_captcha(120,30,5);
$cap->image_dir = $html->url('/').'img/';
$cap->lines_amount = 13;
$cap->en_reload = $html->image('reload.png', array('alt' => __('reload', true), 'title' => __('reload the captcha', true), 'id' => 'frel', 'style' => 'vertical-align:middle'));
?>
</span>
<div>
<span class="display:inline"><?php echo $cap->make_it('HTML');?></span>
<?php echo $form->input('vcode', array('size' => 45, 'class' => 'small input-text', 'label' => array('text' => __('captcha', true).'<sup>*</sup>'), 'error' => array('class' => 'error', 'wrap' => 'small')));?>
</div>
<?php echo $form->submit(__('send',true), array('class' => 'nice medium radius white button'));?>
<?php echo $form->end();?>
<div class="alert-box warning"><?php echo __('fields label with * are required');?></div>
</div>
The problem is: When I use this form from any page (for example posts/view/22) it submits to contacts/add. I want after submit posts/view/22 is rendered with any validation message triggered.

There is no solution for this requirement without Ajax and JSON. It includes submitting the form with Ajax to the contacts controller index action with event handler component activated and then check isAjax then render JSON output retrieved by the post's view and then populates the results.

Related

Form Validation in CakePHP 2

In my view I have
<?= $this->Form->create('Asc201516', array(
'url' => array(
'controller' => 'asc201516s',
'action' => 'submit_asc201516'
),
'class' => 'form-inline',
'onsubmit' => 'return check_minteacher()'
)); ?>
<div class="form-group col-md-3">
<?= $this->Form->input('bi_school_na', array(
'type' => 'text',
'onkeypress' => 'return isNumberKey(event)',
'label' => 'NA',
'placeholder' => 'NA',
'class' => 'form-control'
)); ?>
</div>
<?php
$options = array(
'label' => 'Submit',
'class' => 'btn btn-primary');
echo $this->Form->end($options);
?>
In my Controller, I have
$this->Asc201516->set($this->request->data['Asc201516']);
if ($this->Asc201516->validates()) {
echo 'it validated logic';
exit();
} else {
$this->redirect(
array(
'controller' => 'asc201516s',
'action' => 'add', $semisid
)
);
}
In my Model, I have
public $validate = array(
'bi_school_na' => array(
'Numeric' => array(
'rule' => 'Numeric',
'required' => true,
'message' => 'numbers only',
'allowEmpty' => false
)
)
);
When I submit the form, logically it should not get submitted and print out the error message but the form gets submitted instead and validates the model inside controller which breaks the operation in controller.
You have to check validation in your controller like
$this->Asc201516->set($this->request->data);
if($this->Asc201516->validates()){
$this->Asc201516->save($this->request->data);
}else{
$this->set("semisid",$semisid);
$this->render("Asc201516s/add");
}
You will have your ID there in variable $semisid, or you can set data in $this->request->data = $this->Asc201516->findById($semisid);

Add function in cakephp suddenly stopped working

I'm new to cakePHP, so I may be missing something obvious.
I have an add form that was working and saving to the database, and suddenly stopped. I didn't think I added anything significant, mostly just styling stuff...unfortunately my last backup was before I had finished the add function, so I don't have a way to go back to when it worked. If anyone can take a look and see where I'm going wrong, I would appreciate it!
My Task model:
App::uses('AuthComponent', 'Controller/Component');
class Task extends AppModel {
public $belongsTo = 'User';
public $validate = array(
'task_name' => array(
'custom' => array(
'rule' => array('custom', '/^[a-z0-9 ]*$/i'),
'required' => true,
'message' => 'This field accepts letters and numbers only.'
),
'maxLength' => array(
'rule' => array('maxLength', 50),
'message' => 'Task name cannot exceed 50 characters'
)
),
'frequency' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'allowEmpty' => true
)
),
'day' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'allowEmpty' => true
)
),
'user_id' => array(
'numeric' => array(
'rule' => 'numeric'
)
),
'month_type' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false
)
),
'month_number' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false
)
),
'month_day' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'allowEmpty' => true
)
),
'day_number' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false
)
)
);
}
The add function from my TasksController file:
public function add() {
if ($this->request->is('post')) {
$this->Task->create();
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash(__('Task saved!'));
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash(__('The task could not be saved'));
}
}
}
And the form from my tasks/add.ctp file:
<?php
echo $this->Form->create('Task',array('class' => 'taskForm'));
$userId = $this->Session->read('Auth.User.id');?>
<fieldset>
<legend class="welcomeText"><?php echo __('Add a Task'); ?></legend>
<?php
echo $this->Form->hidden('user_id', array('value' => $userId));
echo $this->Form->input('task_name', array('label' => 'Task Name', 'maxLength' => 50));
//set frequency
echo "<p>How often should this task be done?</p>";
$options = array('unset' => 'Decide Later','daily' => 'Daily','weekly' => 'Weekly','monthly' => 'Monthly');
$attributes = array('value' => 'unset','separator' => '<br/>','class' => 'frequencyRadio','legend' => false);
echo $this->Form->radio('frequency', $options, $attributes);
//optional answers
//if "weekly" is selected
echo "<div id=\"weeklyRadio\" >";
echo "<p>Set a day of the week for this task?</p>";
$options = array('unset' => 'Decide later','monday' => 'Monday','tuesday' => 'Tuesday','wednesday' => 'Wednesday',
'thursday' => 'Thursday','friday' => 'Friday','saturday' => 'Saturday','sunday' => 'Sunday');
$attributes = array('value' => 'unset','separator' => '<br/>','class' => 'weeklyRadio','legend' => false);
echo $this->Form->radio('day',$options,$attributes);
echo "</div>";
//if "monthly" is selected
?>
<div id="monthlyRadio">
<p>Schedule this task?</p>
<input type="radio" name="data[Task][month_type]" id="TaskMonthTypeUnset"
value="unset" class="monthlyRadio" required="required" checked="checked" />
<label for="TaskMonthTypeUnset">Decide later</label><br/>
<input type="radio" name="data[Task][month_type]" id="TaskMonthTypeNumber"
value="number" class="monthlyRadio" required="required" />
<label for="TaskMonthTypeNumber">
<?php
echo "On the ";
$options = array(1 => '1st',2 => '2nd',3 => '3rd',4 => '4th',5 => '5th',6 => '6th',7 => '7th',8 => '8th',9 => '9th',
10 => '10th',11 => '11th',12 => '12th',13 => '13th',14 => '14th',15 => '15th', 16 => '16th',
17 => '17th',18 => '18th',19 => '19th',20 => '20th',21 => '21st',22 => '22nd',23 => '23rd',
24 => '24th',25 => '25th',26 => '26th',27 => '27th',28 => '28th',29 => '29th',30 => '30th',31 => '31st');
echo $this->Form->select('month_number',$options,array('value' => null));
echo " of the month";
?>
</label><br/>
<input type="radio" name="data[Task][month_type]" id="TaskMonthTypeDay" value="day" class="monthlyRadio" required="required" />
<label for="TaskMonthTypeDay">
<?php
echo "On the ";
$options = array(1 => '1st',2 => '2nd',3 => '3rd',4 => '4th',5 => '5th',6 => 'last');
echo $this->Form->select('day_number',$options,array('value' => null));
echo "&nbsp";
$options = array('monday' => 'Monday','tuesday' => 'Tuesday','wednesday' => 'Wednesday',
'thursday' => 'Thursday','friday' => 'Friday','saturday' => 'Saturday','sunday' => 'Sunday');
echo $this->Form->select('month_day',$options,array('value' => null));
echo " of the month";
?>
</label>
</div>
<?php
echo $this->Form->submit('Add Task', array('class' => 'formSubmit', 'title' => 'Create Task') );
?>
</fieldset>
<?php echo $this->Form->end(); ?>
There is also a javascript file that shows and hides the optional radio buttons, but I assume that wouldn't have anything to do with why it stopped saving to the database.
When I click the "Add Task" button on the form, it doesn't do anything at all (doesn't save to the database, and doesn't redirect to the index.ctp view like it used to). No idea what I'm missing here!
UPDATE
Fixed the problem! The places in my form where I specified a default value of null, it was passing an empty string. The data model was expecting numeric values for 'month_number' and 'day_number,' so it wasn't processing.
I fixed it by adding 0 => '' to the selection list, and specifying 0 as the default value, and now it works fine.
Thanks for the help!
I don't see errors in your code.
Add this in the controller add and make a debug for more information about what happens.
public function add() {
$this->loadModel('Task');
debug($this->request->is('post')); //try this first
//debug($this->request); //after try this
if ($this->request->is('post')) {
$this->Task->create();
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash(__('Task saved!'));
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash(__('The task could not be saved'));
}
}
}
loadModel adds this. update your question with that display the debug, and I update mi answer.
It looks like you have the submit form button assigned to a different class, which is why its not firing the form.
echo $this->Form->submit('Add Task', array('class' => 'formSubmit', 'title' => 'Create Task') );
Try changing it to either of the following
echo $this->Form->submit('Add Task', array(
'class' => 'taskForm',
'title' => 'Create Task'));
echo $this->Form->button('Add Task', array(
'class' => 'taskForm',
'title' => 'Create Task',
'action' => 'submit;));
or amend the form ending tag to see if it fires properly.
Change this
echo $this->Form->end();
to
echo $this-Form->end('Submit');

How to call ajax through Bootstrap button in yii

I want to use Ajax through bootstrap button in Yii, and want to pass textfield values though that Ajax call.
here's the button code, where should i put the Ajax code for this button.
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'button', 'label'=>'ADD')); ?>
try this
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'button', 'label'=>'ADD',
'ajaxOptions' => array(
'type' => 'Post',
'url' => $this->createURL('url'),
'data' => Yii::app()->request->csrfTokenName."=".Yii::app()->request->getCsrfToken()."&action=cancel",
'success'=>"js:function(vals){
}",
)
)); ?>
another eg:
$this->widget('bootstrap.widgets.TbButton', array(
'buttonType' => 'ajaxButton',
'label' => 'Label Here',
'type' => 'danger',
'icon' => 'play white',
...
'ajaxOptions' => array(
'success' => '...',
'error' => '...',
'beforeSend' => '...',
)
));

Yii renders only one page without layout

I have a weird problem. I copied my website into production environment (from windows to ubuntu). I correct few big/small letter issues and app started to work fine. Until I entered one page that looks like it's being rendered without layout. There is no error.
Also - firebug shows no css styles or anything. At HTML source there is lack of layout code too.
What could be the reason of that?
EDIT:
controller part:
$dataProvider = Projects::model()->getInviteProjectsProvider();
$this->render('invite', array(
'dataProvider' => $dataProvider
));
It returns CActiveDataProvider.
View:
<?php
$this->breadcrumbs=array(
'Projekty' => array('admin'),
'Zapraszanie',
);
$this->renderPartial('_allMenu');
?>
<link rel="stylesheet" type="text/css" href="<?php echo $this->module->assetsUrl; ?>/css/projects.css"/>
<h1>Projekty aktywne - zapraszanie</h1>
<?php
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id' => 'invite-grid',
'type' => 'striped condensed',
'dataProvider' => $dataProvider,
'rowCssClassExpression' => '($data->leftCustomers<100) ? "error":""',
'columns' => array(
array(
'name' => 'idProject',
'htmlOptions' => array('width' => '60px', 'style' => 'text-align: right;', 'class' => 'gridIdColumn'),
),
'name',
array(
'name' => 'leftCustomers',
'header' => 'Pozostało <i class="icon-info-sign" rel="tooltipbootstrap" data-original-title="Gdy wartość ta jest mniejsza niż 100 - rekord jest podświetlony na czerwono"/>',
),
'confirmStart',
'presentationDate',
array(
'class' => 'bootstrap.widgets.TbRelationalColumn',
'name' => 'Statystyki',
'value' => '"Pokaż"',
'url' => $this->createUrl('dynamicProjectStats')
),
array(
'header' => 'Postęp <i class="icon-info-sign" rel="tooltipbootstrap" data-original-title="Liczba zaproszeń / Limit zaproszeń"/>',
'value' => function($data)
{
$prc = round(($data->projectMaxInvites > 0) ? ($data->projectInvites)/ $data->projectMaxInvites * 100 : 0, 2);
Controller::widget('bootstrap.widgets.TbProgress', array(
'percent' => $prc,
'htmlOptions' => array(
'style' => 'height: 20px; margin-bottom: -20px',
'rel' => 'tooltipbootstrap',
'data-original-title' => $prc." %",
),
));
},
),
array(
'class' => 'bootstrap.widgets.TbButtonColumn',
'template' => '{view}{update}{delete}',
'htmlOptions' => array(
'style' => 'width: 40px;',
),
),
array(
'header' => '',
'htmlOptions' => array('style' => 'width: 43px'),
'value' => function($data)
{
$this->renderPartial('partials/_actionMenu', array('idProject' => $data->idProject, 'activated' => true, 'afterAction' => 'removeActiveProject'));
}
),
array(
'header' => '',
'value' => function($data)
{
$this->renderPartial('partials/_statMenu', array('idProject' => $data->idProject, 'showIcon' => true));
}
),
)
));
?>
I noticed that if I comment out the columns where function($data) is used - it shows fine. When I leave it - there is no layout displayed.
EDIT2:
Maybe I should notice the fact that inside partials/_statMenu and partials/_actionMenu there is a bootstrap.widgets.TbButtonGroup widget rendered.
Try:
Yii::app()->controller->renderPartial(...)
Instead of:
$this->renderPartial(...)

Post multipart data with Zend Forms

I want to post arrays with Zend.
html form:
<form id="form" class="form-container" action="<?php echo $this->form->getAction(); ?>" method="post" enctype="multipart/form-data">
<?php foreach ($this->projects as $item): ?>
<?php echo $this->form->time_on_project; ?>
<?php echo $this->form->comment; ?>
<?php endforeach; ?>
Zend Form:
$this->addElement('text', 'time_on_project[]', array(
'label' => 'Время(формат час:минуты):',
'required' => true,
'attribs' => array('class' => 'form-field', 'required' => 'required', 'placeholder' => 'Введите время в формате час:минуты'))
);
$this->addElement('textarea', 'comment[]', array(
'label' => 'Что сделано:',
'required' => false,
'attribs' => array('class' => 'form-field', 'style' => 'height: 100px')
));
After that, my inputs not displayed. How to make it right?
Thanks for help.
you could try doing:
$this->addElement('text', 'time_on_project', array(
'isArray' => true,
'value' => '237',
'label' => 'Время(формат час:минуты):',
'required' => true,
'attribs' => array('class' => 'form-field', 'required' => 'required', 'placeholder' => 'Введите время в формате час:минуты'))
'decorators' => Array(
'ViewHelper'
),
));

Categories