Can't validate form CakePHP 3 - forms

I'm new on CakePHP and I can't validate a login form. I'm getting the following error: Notice (8): Undefined variable: user [APP/Template\Users\login.ctp, line 5]
I already tried to use this code: <?= $this->Form->create('User'); ?> The error is removed but the validation doesn't works.
Can someone help me?
login.ctp:
<br>
<div class="index large-4 medium-5 large-offset-4 medium-offset-4 columns">
<div class="panel">
<h2 class="text-center">Login</h2>
<?= $this->Form->create($user); ?>
<?php
echo $this->Form->input('email');
echo $this->Form->input('password');
?>
<?= $this->Form->submit('Login', array('class' => 'button')); ?>
<?= $this->Form->end(); ?>
</div>
</div>
login function - UsersController.php:
// Login
public function login()
{
if($this->request->is('post'))
{
$user = $this->Auth->identify();
if($user)
{
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'comentario']);
}
// Erro no Login
$this->Flash->error('Erro de autenticação');
}
}

First of all, change this line
<?= $this->Form->create($user); ?>
to this
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
Then, you can simplify your submit like this
<?= $this->Form->button(__('Login')); ?>
Make sure you create UsersTable.php in you src/Model/Table and put this code
// src/Model/Table/UsersTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('username', 'A username is required')
->notEmpty('password', 'A password is required')
}
}
It's not good using redirect the specific controller inside login method. Change it:
return $this->redirect($this->Auth->redirectUrl());
Then tell your Auth Component where user should be redirect after login
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Articles',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
And the most important. Read Authentication and Authorization Tutorial

Related

Is there a way to call modeless form in pages using cakephp3

as what I read online it will only be available for like this
http://localhost/xxxxx/contact then the form will display
but I want it to display in many pages like contact us, or about us page
when i call this pages I want the form appear in the content?
Template
index.ctp
<?= $this->Form->create($contact); ?>
<?= $this->Form->input('name'); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('body'); ?>
<?= $this->Form->button('Submit'); ?>
<?= $this->Form->end(); ?>
ContactController.php
<?php
// In a controller
namespace App\Controller;
use App\Controller\AppController;
use App\Form\ContactForm;
class ContactController extends AppController
{
public function index()
{
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
$this->Flash->success('Your message has been sent; we\'ll get back to you soon!');
$this->request->data['name'] = null;
$this->request->data['email'] = null;
$this->request->data['body'] = null;
} else {
$this->Flash->error('There was a problem submitting your form.');
}
}
$this->set('contact', $contact);
}
}
?>
ContactForm.php
<?php
namespace App\Form;
use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;
use Cake\Mailer\Email;
class ContactForm extends Form
{
protected function _buildSchema(Schema $schema)
{
return $schema->addField('name', 'string')
->addField('email', ['type' => 'string'])
->addField('body', ['type' => 'text']);
}
protected function _buildValidator(Validator $validator)
{
return $validator->add('name', 'length', [
'rule' => ['minLength', 10],
'message' => 'Please enter your name'
])->add('email', 'format', [
'rule' => 'email',
'message' => 'Please enter a valid email address',
])->add('body', 'length', [
'rule' => ['minLength', 25],
'message' => 'Please enter your message text',
]);
}
protected function _execute(array $data)
{
// Send an email.
return true;
}
}
You can fixed it by moving the contact template form into the element so that it will be available in any pages.
inside element in the contact folder, form below must be present
<legend><?= __('Our Form') ?></legend>
<fieldset>
<?php
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('body');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end(); ?>
then in your pages
you can just call
<?php
echo $this->element('contact/index');
?>
assuming you created index.ctp inside contact folder in element
Hope it solved your problem.

cakephp3- unable to post form data to controller function

I have a contact us form and user enter data and submits it. This data needs to accessed in controller function so I can send a mail to admin informing about the user request recently received.
But when I press submit button, nothing happens. Form just reloads and the contactus form (view page) is shown to the users. I don't know why the data is not getting passed to the controller function.
I'mm new to CakePHP framework and I'm using CakePHP3 for development purposes.
Here is my form:
<?php echo $this->Form->create(null, ['url' => ['controller' => 'Pages', 'action' => 'contactus']]); ?>
<div class="col-md-6">
<?php echo $this->Form->input('fname', ['placeholder' => 'Your name.' , 'id' => 'fname', 'required' => 'required']); ?>
</div>
<div class="col-md-6">
<?php echo $this->Form->input('mail', ['placeholder' => 'Your email.' , 'id' => 'mail', 'required' => 'required']); ?>
</div>
<div class="col-md-6">
<?php echo $this->Form->input('subject', ['placeholder' => 'Write something.', 'id' => 'subject']); ?>
</div>
<div class="col-md-9">
<?php echo $this->Form->button(__('Submit')); ?>
</div>
<?php echo $this->Form->end(); ?>
And my controller function is:
public function contactus()
{
$pages ='';
if ($this->request->is('post'))
{
$pages = $this->request->data('Contact');
}
$this->set(compact('pages'));
$this->set('_serialize', ['pages']);
}
Can anyone tell me the mistakes I made?
I think your form is submitting but not through the post method. So I would like to say you that, please make the bellow changes before submitting the form.
$pages ='';
if ($this->request->is('post'))
{
echo "Request is post";die;
$pages = $this->request->data('Contact');
}else{
echo "request is not post";die;
}
$this->set(compact('pages'));
$this->set('_serialize', ['pages']);
Now check, which is printing in the display. Then I can help you further.
Remember: - fill the form, then after change the controller method, then press submit method.

Yii2 DatePicker within Modal

when I use the kartik\date\DatePicker within Modal,but it's report error that like https://******.com/assets/d9620747/css/bootstrap-datepicker3.css.map Failed to load resource: the server responded with a status of 404 (Not Found).plz help me;
My Controller's code:
public function actionBook($id = null)
{
$ticket = $this->findModel($id);
$model = new TicketOrder();
if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
// userCreate scenario
$model->scenario = 'create';
} else {
return $this->renderAjax('book', [
'ticket' => $ticket,
'model' => $model,
]);
}
}
My View's code:
<?php
Modal::begin([
'id' => 'create-modal',
'header' => '<h4 class="modal-title">订票</h4>',
'size' => 'modal-lg',
// 'footer' => 'Close',
]);
Modal::end();
?>
<?php
$js = <<<JS
$(function(){
$(".modal-wraper").click(function(){
var id = $(this).attr('data-id');
var url = "/sights/product-ticket/book?id=" + id;
$.get(url,{},function(data){
$(".modal-body").html(data);
});
$('#create-modal').on('shown.bs.modal', function(){
$('[data-toggle="popover"]').popover();
});
$("#create-modal").modal('show');
});
});
JS;
$this->registerJs($js);
My ajaxRender view's code:
<?php
use kartik\form\ActiveForm;
use kartik\date\DatePicker;
?>
<h3>由于资源方过多,建议一个手机号只购买一张票。</h3>
<?php
$form = ActiveForm::begin([
'type' => ActiveForm::TYPE_HORIZONTAL,
]);
?>
<?= $form->field($model, 'fullname')->textInput() ?>
<?= $form->field($model, 'mobile')->textInput() ?>
<?= $form->field($model, 'plantime')->widget(DatePicker::className(), [
'type' => DatePicker::TYPE_COMPONENT_APPEND,
]) ?>
<?= $form->field($model, 'comment')->textarea() ?>
<div class="button-group">
<?= \yii\helpers\Html::a('关闭', ['#'], ['class' => "btn btn-primary", 'data-dismiss' => "modal"]) ?>
<?= \yii\helpers\Html::button('购买', ['class' => 'btn btn-success pull-right', 'type' => 'submit']) ?>
</div>
<?php
$form->end();
?>
Like this:
image
I got error when I click the DatePicker Button.
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (bootstrap-datepicker3.css.map, line 0)
This issue has been already resolved. See it on GitHub.
Upgrade datepicker to version 1.4.2.

yii2 loading pjax form dynamically

Problem: I want to update GridView in pjax style but it redirect to the form creation page.
What the code below does:
Having an index page with GridView to display data list and open a form in a modal window to create new record. The form code is added into the modal dynamically.
When click on "Create Country" button on index page, it calls country/create to get the HTML code of the form and insert it into the modal, then it shows the modal window.
When click on the "Create" button on the form, it submit the form to country/create. This will return the HTML code of the index page, and I want it to update the GridView part, but it does not.
The code:
Controller CountryController.php
class CountryController extends Controller
{
public function actionIndex()
{
return $this->renderIndex();
}
public function actionCreate()
{
$model = new Country();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->renderIndex();
} else {
return $this->renderAjax('_form', [
'model' => $model,
]);
}
}
private function renderIndex()
{
$searchModel = new CountrySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
View index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\web\View;
$this->title = Yii::t('app', 'Countries');
$this->params['breadcrumbs'][] = $this->title;
yii\bootstrap\Modal::begin(['id' => 'modal']);
yii\bootstrap\Modal::end();
?>
<div class="country-index">
<h1><?= Html::encode($this->title) ?></h1>
<div>Current Time: <?= date('Y/m/d H:i:s') ?></div>
<p><?= Html::a(Yii::t('app', 'Create Country'),
['create'],
['class' => 'btn btn-success show-modal']) ?>
</p>
<?php Pjax::begin(['id' => 'pjax-grid']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php
$this->registerJs("$(function() {
$('.show-modal').click(function(e) {
e.preventDefault();
$('#modal').modal('show').find('.modal-body')
.load($(this).attr('href'));
});
});", View::POS_READY, '.show-modal');
?>
View _form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\web\View;
?>
<?php
$this->registerJs(
'$("document").ready(function(){
$("#pjax-create").on("pjax:end", function() {
$.pjax.reload({container:"#pjax-grid"}); //Reload GridView
});
});'
, View::POS_READY, 'pjax-create-end');
?>
<div class="country-form">
<?php yii\widgets\Pjax::begin(['id' => 'pjax-create']) ?>
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => TRUE]]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
</div>
Use Html::button instead Html::a and simple overwrite the content of the modal:
yii\bootstrap\Modal::begin(['id' => 'modal']);
echo '<div id="modal-content"></div>';
yii\bootstrap\Modal::end();
echo Html::button('Create Country', [
'onClick' => 'createCountry("' . Url::to([create]) . '")',
'class' => 'btn btn-primary'
]);
$script = <<< JS
function createCountry(url) {
$('#modal').modal('show').find('#modal-content').load(url);
}
JS
$this->registerJs($script, View::POS_END);

Yii2 saving form with multiple models

Hi I am very close to finish a project but got stuck saving a from with multiple models.
I have a grid that calls a controllers action that calls a form.
public function actionToday() {
$ID = $_GET["0"];
$modelCustomers = Customers::find()->where(['ID' => $ID])->one();;
$today = date("Y-m-d");
$beforeToday = 'DropinDate>'.$today;
$modelAttendance = Attendance::find()->where(['CustomersID' => $ID])->andwhere(['DropinDate' => $today])->one();
return $this->render('//attendance/_form-today-attendance', ['modelCustomers' => $modelCustomers, 'model' => $modelAttendance]);
}
In the form i have 3 main fields to update or in case is not record i need to create a new record.
This is the _form-today-attendance
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
?>
<?php $form = ActiveForm::begin(); ?>
<h3>Your Personal Details</h3>
<?= $form->field($modelCustomers, 'Name')->textInput(['readonly' => true]) ?>
<?= $form->field($model, 'DropinDate')->textInput(['readonly' => true]) ?>
<div class="attendance-form">
<?= $form->field($model, 'Dropin')->checkbox() ?>
<?= $form->field($model, 'Doctor')->checkbox() ?>
<?= $form->field($model, 'Lawyer')->checkbox() ?>
<?= $form->field($model, 'Observation')->textInput(['maxlength' => 250]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
When I debug i cant get anything happend in the Attendence model or the Customers model.
Any ideas?
Thanks a lot,
Eduardo
Try this function and check what you get.
public function actionToday()
{
$ID = $_GET["0"];
$modelCustomers = Customers::find()
->where(['ID' => $ID])
->one();;
$today = date("Y-m-d");
$beforeToday = 'DropinDate>' . $today;
$modelAttendance = Attendance::find()
->where(['CustomersID' => $ID])
->andwhere(['DropinDate' => $today])
->one();
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post();
//do something with $data
}
return $this->render('//attendance/_form-today-attendance', [
'modelCustomers' => $modelCustomers,
'model' => $modelAttendance]);
}
There will be something in array, you can assign it to model instances.