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

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.

Related

Yii 2 Call to a member function saveAs() on string

new to Yii and I am getting this error on a Send Email page. The string in question is the path to the attachment and the attachment name and i am presuming that the saveAs function would expect a string. Any ideas what i am missing?
The form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\emails */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="emails-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'reciever_name')->textInput(['maxlength' => 50]) ?>
<?= $form->field($model, 'receiver_email')->textInput(['maxlength' => 200]) ?>
<?= $form->field($model, 'subject')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'content')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'attachment')->fileInput(['maxlength' => 255]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
and the controller:
public function actionCreate()
{
$model = new emails();
if ($model->load(Yii::$app->request->post())) {
// upload the attachment
$model->attachment = UploadedFile::getInstance($model, 'attachment');
if($model->attachment)
{
parent::init();
$time = time();
//$model->attachment->saveAs('attachments/'.$time.'.'.$model->attachment->extension);
//$model->attachment = 'attachments/'.$time.'.'.$model->attachment->extension;
}
if($model->attachment)
{
$value = Yii::$app->mailer->compose()
->setFrom(['my_email#gmail.com' => 'Paul'])
->setTo ($model->receiver_email)
->setSubject ($model->subject)
->setHtmlBody ($model->content);
foreach ($model->attachment as $file) {
//$filename = 'attachments/'.$time.'.'.$model->attachment->extension;
$filename = 'attachments/file.jpg';
//var_dump($filename);die();
$file->saveAs($filename);
$value->attach('attachments/file.jpg');
//$value->attach('attachments/'.$time.'.'.$model->attachment->extension);
}
$value->send();
}else{
$value = Yii::$app->mailer->compose()
->setFrom(['my_email#gmail.com' => 'Paul'])
->setTo($model->receiver_email)
->setSubject($model->subject)
->setHtmlBody($model->content)
->send();
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
I have tried absolute paths as well as dymanic paths, but all has the same output, i am stuck
Save as() function require the actual path. So that is issue. Please make sure your path should be correct and accessible.

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 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);

Can't validate form CakePHP 3

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

Zend Framework multiple form elements names

I have multiple Zend Framework(v1.12) forms in my application.
Main form:
<?php
class Application_Form_Main extends Zend_Form
{
public function init()
{
$this->setMethod('post')->setAction('some/url');
}
}
?>
My subform:
<?php
class Application_Form_User extends Zend_Form_SubForm
{
public function init()
{
//first name element
$this->addElement('text',
'first_name',
array(
'label' => 'Name',
'required' => true,
'filters' => array('StringTrim')
)
);
//last name element
$this->addElement('text',
'last_name',
array(
'label' => 'Surname',
'required' => true,
'filters' => array('StringTrim')
)
);
$this->setElementDecorators(array(
'ViewHelper',
'Errors'
));
}
}
?>
In my custom controller (for example UsersController.php) Im rendering main form with multiple user subforms:
<?php
$mainForm = new Application_Form_Main();
for($i=0; $i<2; $i++){
$userForm = new Application_Form_User();
$mainForm->addSubForm($userForm, 'user_'.($i+1));
}
//passing main form to the template
$this->view->mainForm = $mainForm;
?>
So Im getting the form with 2 users first_name and last_name fields.
In my template Im rendering form this way:
<form action="<?php echo $this->mainForm->getAction(); ?>"
enctype="<?php echo $this->form->getEnctype(); ?>"
method="<?php echo $this->form->getMethod(); ?>"
">
<?php echo $this->mainForm->getSubForm('user_1')->first_name; ?>
<?php echo $this->mainForm->getSubForm('user_1')->last_name; ?>
<?php echo $this->echo $this->mainForm->getSubForm('user_2')->first_name; ?>
<?php echo $this->echo $this->mainForm->getSubForm('user_2')->last_name; ?>
</form>
The problem is first_name and last_name text field names are identical in both forms. How can I make it to have unique names? If I output the form:
<?php echo $this->mainForm; ?>
Then everything is ok, I get different field names.
So any ideas?