How the link in email content work with cakephp3 - email

I want that the user activate his account in clicking the link in the email ,my problem that the link didn't work
my userscontroller
if ($this->Users->save($user)) {
$email = new Email();
$email->transport('mailjet')
->to('xxxxxxx#gmail.com')
->template('add')
->emailFormat('html')
->viewVars(['nom' =>$user['first_name'],
'url'=>['controller'=>'users','action'=>'active',$user],
'user'=>$user])
->subject('fffff')
->send();
the function active($user) code
public function active($user){
$user = $this->Users->patchEntity($user, [
'state' => 1]);
$this->redirect('../xxxxxHome/Acceuil');
}
template/Email/html/add.ctp
<?php
use Cake\Routing\Router;
use Cake\Routing;
?>
<strong>Bonjour <?php echo $nom ?></strong>
<p >Pour activer ce compte suivez le lien </p>
<?php echo $this->Html->link('Activer mon compte',Router::url($url, true), ['escape' => false]);?></p>`
the problem when i call the structure of the url

Related

Validating a form that is not ‘add’ or ‘edit’ in Cakephp3.3

I’m learning Cakephp3.3 and have run into a problem trying to validate a form prior to saving.
I created a new form in ‘src/Template/Users’ called ‘register.ctp’ and added an action called ‘register’ in ‘src/Controller/UsersController’.
I want to validate form submissions before saving but can’t figure out how to make this work.
FWIW, pre-save validation works perfectly for the ‘add’ and ‘edit’ forms, though I think this happens by default in Cakephp3.
Is there a way to make these same validation rules apply for the ‘register’ form?
FYI, the 'register' action is actually updating an existing user record previously created for an anonymous user.
Here's the controller action:
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
class UsersController extends AppController
{
//<snipped methods>
public function register()
{
if($this->request->session()->read('Auth.User'))
{
$id = $this->request->session()->read('Auth.User.id');
if ($this->request->is(['patch', 'post', 'put']))
{
$user = $this->Users->get($id, [
'contain' => []
]);
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user))
{
$this->Flash->success(__('Your free trial period has started.'));
return $this->redirect("/Home/index");
}
else
{
$this->Flash->error(__('We were unable to start your trial. Please, try again.'));
}
}
}
else
{
$this->Flash->error(__('Your demo session has expired. Please start again.'));
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
}
Here's the UsersTable Model with the validation rules:
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->email('email')
->requirePresence('email')
->notEmpty('An email address is required.');
$validator
->requirePresence('password')
->notEmpty('A password is required.');
$validator
->requirePresence('firstname')
->notEmpty('firstname')
->add('firstname', 'minlength',['rule' => ['minlength', 1]]);
$validator
->requirePresence('lastname')
->notEmpty('lastname')
->add('lastname', 'minlength',['rule' => ['minlength', 1]]);
$validator
->integer('status')
->requirePresence('status', 'create')
->notEmpty('status');
$validator
->add('role', 'inList', [
'rule' => ['inlist', ['admin','author','subscriber']],
'message' => 'Please enter a valid role.'
]);
$validator
->requirePresence('referer', 'create')
->allowEmpty('referer');
$validator
->integer('plan_id')
->requirePresence('plan_id', 'create')
->notEmpty('plan_id');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
}
And here's the register.ctp form:
<div class="users form large-12 columns ">
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Sign Up For Your No-Risk Free Trial!') ?></legend>
<?= $this->Form->input('firstname'); ?>
<?= $this->Form->input('lastname'); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('password'); ?>
</fieldset>
<?= $this->Form->button(__('Start My Free Trial Now')) ?>
<?= $this->Form->end() ?>
</div>
Any help would be greatly appreciated!
if you want to save then the Default validation rules will be apply. if you don't want to apply the default rule then just add the 'validate' => false param
$user = $this->Users->patchEntity($user, $this->request->data,['validate' => false])
if you want to custom validation rule only for register options then need to create new function in your TABLE
class UsersTable extends Table
{
public function validationRegister($validator)
{
$validator
->email('email')
->requirePresence('email')
->notEmpty('An email address is required.');
$validator
->requirePresence('password')
->notEmpty('A password is required.');
$validator
->requirePresence('firstname')
->notEmpty('firstname')
->add('firstname', 'minlength',['rule' => ['minlength', 1]]);
return $validator;
}
}
Now set the 'validate' => 'register' param in your controller newEntity or patchEntity Funciton
$user = $this->Users->patchEntity($user, $this->request->data,['validate' => 'register'])

Button submit's value not transmitted in POST

I am using Yii2 and I want to create comment functionality on post using Pjax widget.
The comment windows displays all the existing comments for the post adding an edit button to the ones that belongs to the connected user in order to permit changes.
Under this list of comments,there is a form including a textarea and a submit button to allow comment creation.
Each time the user click on an already existing comment 's edit button, a form is displayed to allow update.
How all this actually runs and the trouble I meet:
I can update an existing comment an infinite number of times, and it is what I want.
If, just after refreshing the view post page, I enter a new comment, it
is correctly submitted. But I cannot enter an other one and I want to be able to post more than one. The second time, it appears that the POST contains the content of the comment but nothing
regarding the submit button. Thus I cannot recognize which button has
been clicked.
The same thing happens after I have changed an
existing comment i.e. I cannot create a new comment for the same
reason – nothing about the submit button in the POST.
My question
How comes the submit button is transmitted in the POST only if it is the first one used and it is the first time it is used after a refresh of the page?
Here are the relevant code parts
1-Controller
/**
* display a post
*#param integer $id
*
* return a view
*/
public function actionView ($id){
$post = $this->findModel($id);
$comment=$this->manageComment($post);
return $this->render('view', [
'post_model' => $post,
'comment_model' => $comment,
]);
}
/*
* deals with the post according to the submit value
* if submitted and return the comment under treatment
* otherwise – not submitted – return a new comment
*
*#param $post the post that holds the comments
*
* return a Comment model
*/
protected function manageComment($post)
{
$comment=new Comment;
if(isset($_POST['Comment']) )
{
switch ($_POST['Submit']) {
case 'create':
$comment->attributes=$_POST['Comment'];
if($post->addComment($comment,false))
{
//la création a réussi
if($comment->status==Comment::STATUS_PENDING)
Yii::$app->session->setFlash('success',
Yii::t('app','Thank you for your comment.
Your comment will be visible once it is approved.'));
//on renouvelle le commentaire pour éviter d'avoir
//un bouton update (mise à jour)
return new Comment;
}
break;
case 'update':
$comment=Comment:: find()
->where(['id' => $_POST['Comment']['id']])
->one();
if($comment->attributes=$_POST['Comment']){
if($post->addComment($comment,true))
{
//update successful
if($comment->status==Comment::STATUS_PENDING)
{Yii::$app->session->setFlash('success',
Yii::t('app','Thank you for your comment.
Your comment will be visible once it is approved.'));}
$comment= new Comment;
return $comment;
} else {
//la mise à jour a échoué
$comment= new Comment;
return $comment;
}
}else{echo'load failed'; exit();}
break;
case 'edit':
// echo $_POST['Comment']['id']; exit();
$comment->id = $_POST['Comment']['id'];
return $comment;
break;
default:
}
}
//creation successful
return $comment;
}
2-In Post view
<!--comment_model is passed by PostController-->
<?= $this->render('#app/views/comment/_create-form',
['model' => $comment_model, 'post' => $post_model]); ?>
3 - the _create-form view
<div class="comment-form">
<?php Pjax::begin([ ]);?>
<!-- this bloc must be part of the Pjax in order for the new
comment to appear immediately -->
<div class="comment">
<h4 ><?= Yii::t('app','Comments by users')?></h4>
<div class="comments">
<?php $comments= Comment::find()
->where (['post_id' => $post->id ])
->andWhere(['status' => true])
->all();
foreach($comments as $com){
$identity= User::findIdentity($com->user_id);
$firstname=$identity->firstname;
familyname=$identity->familyname;
$date= Utils::formatTimestamp($com->created_at);
$txt1 = Yii::t('app','Posted by ');
$txt2 = Yii::t('app',' on ');
$text_header =$txt1. $firstname.' '.$familyname.$txt2.$date;
//here we check that $model->id is defined an equal to $com->id
//to include edition form
if (isset($model->id) && ($model->id == $com->id) )//
{
// echo Yii::$app->user->identity->id. ' '.$com->user_id; exit();
echo $this->render(
'_one-comment',(['com' => $com,
'text_header' => $text_header,
'submit_btn' => false,
'with_edit_form' => true]));
} else
{
$submit_btn=false;
if (Yii::$app->user->identity->id == $com->user_id) $submit_btn=true; else $submit_btn=false;
echo $this->render('_one-comment',(['com' => $com, 'text_header' => $text_header, 'submit_btn' => $submit_btn,'with_edit_form' => false]));
}
}?>
</div>
<!--this div should be between Pjax::begin and Pjax::end otheswise it is not refreshed-->
<div id="system-messages" >
<?php foreach (Yii::$app->session->getAllFlashes() as $type => $message): ?>
<?php if (in_array($type, ['failure','success', 'danger', 'warning', 'info'])): ?>
<?= Alert::widget([
'options' => ['class' => ' alert-dismissible alert-'.$type],
'body' => $message
]) ?>
<?php endif ?>
<?php endforeach ?>
</div>
<?php
$form = ActiveForm::begin([
'options' => ['data' => ['pjax' => true]],//'id' => 'content-form'
// more ActiveForm options
]); ?>
<?= $form->field($model, 'content')
->label('Postez un nouveau commentaire')
->textarea(['rows' => 6]) ?>
<?= Html::submitButton('Create comment',
['content' => 'edit','name' =>'Submit','value' => 'create']) ?>
<?php
ActiveForm::end();?>
</div>
<?php Pjax::end()
?>
</div>
4 - the _one-comment view
<div class="one-comment">
<div class="comment-header">
<?php echo $text_header;?>
</div>
<div class="comment-text">
<?php echo $com->content;?>
</div>
<div class="comment-submit">
<?php
if ($with_edit_form)
{
// echo "with edit ".$com->id; exit();
echo $this->render('_update-one-comment',(['com' =>$com]));
} else
{
if($submit_btn){
$form = ActiveForm::begin([
'options' => [ 'data' => ['pjax' => true]],//'name' => 'one','id' => 'com-form-'.$com->id,
// more ActiveForm options
]); ?>
<?= $form->field($com, 'id')->hiddenInput()->label(false);?>
<div class="form-group">
<?= Html::submitButton('', [
'class' => 'glyphicon glyphicon-pencil sub-btn',
'content' => 'edit',
'name' =>'Submit','value' => 'edit']) ?>
</div>
<?php
ActiveForm::end();
}
}?>
</div>
</div>
5 the _update-one-comment form
//echo 'dans update-one-comment';print_r($com->toArray()); exit();
$form = ActiveForm::begin([
'options' => [ 'data' => ['pjax' => true]],//'name' => 'edit-one','id' => 'edit-com-form-'.$com->id,
// more ActiveForm options
]); ?>
<?= $form->field($com, 'id')->hiddenInput()->label(false);?>
<?= $form->field($com, 'created_at')->hiddenInput()->label(false);?>
<?= $form->field($com, 'updated_at')->hiddenInput()->label(false);?>
<?= $form->field($com, 'content')
->label('Mise à jour commentaire')
->textarea(['rows' => 6]) ?>
<div class="form-group">
<?= Html::submitButton($com->isNewRecord ?
Yii::t('app', 'Create comment') :
Yii::t('app', 'Update comment'), ['class' => $com->isNewRecord ?
'btn btn-success' :
'btn btn-primary','name' =>'Submit','value' => 'update']) ?>
</div>
<?php
ActiveForm::end();
?>
6- the Post model 's addComment()
public function addComment($comment, $up=false)
{
if(Yii::$app->params['commentNeedApproval'])
{$comment->status=Comment::STATUS_PENDING;}
else {$comment->status=Comment::STATUS_APPROVED;}
$comment->post_id=$this->id;
$comment->user_id=Yii::$app->user->identity->id;
if($up){
$test=$comment->update();
if($test) {//($comment->save(false)){
Yii::$app->session->setFlash('success',Yii::t(
'app','The comment has been succesfully updated.'));
return true;
}
Yii::$app->session->setFlash('failure',Yii::t(
'app','The comment could not be updatded.'));
} else
{ //création
if($comment->save()){
Yii::$app->session->setFlash('success',
Yii::t('app','The comment has been succesfully recorded.'));
return true;
}
Yii::$app->session->setFlash('failure',
Yii::t('app',$up.false.'The comment could not be recorded.'));
}
return false;
}
Why are you counting on the submit button name / value to figure out what you need to do?
$_POST['Comment']['id'] is a much better indicator of what needs to done. If it is there update otherwise create.
Also make sure the model does not allow editing of comments posted by others.
The model should not set flash messages, that is a job for the controller.
"I can update an existing comment an infinite number of times." of course you can, from what you told us there is nothing that would say you should not be able to. And you are not checking to prevent that.
As the submit button's value is not always transmitted in the post (it works with Chromium but not with Firefox), I solved my problem adding a hidden field in the forms and used it instead of the submit button's value.

trying to send email with laravel, get an error. What does this mean?

I'm trying to send email with laravel, get an error. What does this mean?
stream_set_blocking() expects parameter 1 to be resource, null given
Edit: Mail code.
controller:
public function postSubmit(Request $request)
{
Mail::send('emails.contact', ['data' => $request->all()], function ($m) {
$m->from(config('mail.from.address'), config('mail.from.name'));
$m->to('xxxxx', 'xxxx')->subject('Contact Form Submitted');
});
}
Routes:
Route::get('/contact', 'ContactController#index');
Route::post('/contact/submit', 'ContactController#postSubmit');
View:
<form role="form" id="feedbackForm" data-toggle="validator" data-disable="false" method="POST" action="{{ url('contact/submit') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
Send view:
<strong>You have a new feedback from contact page!</strong>
<p><strong>Name: </strong> {{$data['name']}}</p>
<p><strong>Email: </strong> {{$data['email']}}</p>
<p><strong>Message: </strong> {{$data['message']}}</p>
Edit2: disable_functions: "phpinfo, system, exec, passthru, proc_open, shell_exec, popen, setlimit, mysql_pconnect, stream_socket_client"
These functions are disabled by the host. (They won't enable them due security reasons). I've been informed that I can use mail(). How does that work exactly?! (smtp, username, password, etc..)
This is how I managed to get laravel to send an email.
Yes, of course. Here's the solution that I used in order to configure email for laravel.
indexmail.php, root folder
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="your-email#your-domain.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../contact.php?msg=Successful Submission! Thankyou for contacting us.");
else
header("Location:../contact.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
?>
routes.php
Route::post('/contact/submit', 'ContactController#postSubmit');
config/mail.php
'from' => ['address' => 'Sender#email.com', 'name' => 'MyName'],
'pretend' => false,
email view.
<strong>You have a new feedback from contact page!</strong>
<p><strong>Name: </strong> {{$data['name']}}</p>
<p><strong>Email: </strong> {{$data['email']}}</p>
<p><strong>Message: </strong> {{$data['message']}}</p>
contact form.
<form role="form" id="feedbackForm" data-toggle="validator" data-disable="false" method="POST"
action="{{ url('contact/submit') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}"/>
app/Http/Requests/ContactFormRequest.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class ContactFormRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'message' => 'required',
];
}
}
app/User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Let me know if it works! original refference

cakephp multiple forms with same action

I've got on my page several News, to every News we can add comment via form.
So actually I've got 3 News on my index.ctp, and under every News is a Form to comment this particular News. Problem is, when i add comment, data is taken from the last Form on the page.
I don;t really know how to diverse them.
i've red multirecord forms and Multiple Forms per page ( last one is connected to different actions), and i don't figure it out how to manage it.
Second problem is, i can't send $id variable through the form to controller ( $id has true value, i displayed it on index.ctp just to see )
This is my Form
<?php $id = $info['Info']['id']; echo $this->Form->create('Com', array('action'=>'add',$id)); ?>
<?php echo $this->Form->input(__('Com.mail',true),array('class'=>'form-control','field'=>'mail')); ?>
<?php echo $this->Form->input(__('Com.body',true),array('class'=>'form-control')); ?>
<?php echo $this->Form->submit(__('Dodaj komentarz',true),array('class'=>'btn btn-info')); ?>
<?php $this->Form->end(); ?>
and there is my controller ComsController.php
class ComsController extends AppController
{
public $helpers = array('Html','Form','Session');
public $components = array('Session');
public function index()
{
$this->set('com', $this->Com->find('all'));
}
public function add($idd = NULL)
{
if($this->request->is('post'))
{
$this->Com->create();
$this->request->data['Com']['ip'] = $this->request->clientIp();
$this->request->data['Com']['info_id'] = $idd;
if($this->Com->save($this->request->data))
{
$this->Session->setFlash(__('Comment added with success',true),array('class'=>'alert alert-info'));
return $this->redirect(array('controller'=>'Infos','action'=>'index'));
}
$this->Session->setFlash(__('Unable to addd comment',true),array('class'=>'alert alert-info'));
return false;
}
return true;
}
}
you are not closing your forms
<?php echo $this->Form->end(); ?>
instead of
<?php $this->Form->end(); ?>
for the id problem you should write
echo $this->Form->create(
'Com',
array('action'=>'add/'.$id
)
);
or
echo $this->Form->create(
'Com',
array(
'url' => array('action'=>'add', $id)
)
);

Forms CakePhp 1 form multiple tables

I have two controllers partners and deals.
When I add deal there is field partner id and in cakephp this generates a dropdown with all the partners. Is there away that if the user wants to add a new partner they could click a checkbox and add form would appear. Tried adding the partner input boxes and yes this creates new partner but it in the deal table it puts the partner id of the selected partner from the drop down not the new partner.
Deal Veiw
<div class="deals form">
<h2>Add New Deal</h2>
<p>Use the form below to fill in the new deals details.</p>
<?php echo $form->create('Deal');?>
<?php
echo $cksource->create();
echo $form->input('title');
echo $form->input('price');
echo $form->input('market_price');
echo $form->input('discount');
echo $form->input('buy_link');
echo $form->input('image');
$config['toolbar'] = array(
array( 'Source', '-', 'Bold', 'Italic', 'Underline', 'Strike', '-','BulletedList' ),
array( 'Image', 'Link', 'Unlink', 'Anchor' )
);
?><label>Deal Highlights</label><?php
echo $cksource->ckeditor('highlights', array('config'=>$config));
?><label>Deal Fine Print</label><?php
echo $cksource->ckeditor('fine_print', array('config'=>$config));
echo $form->input('description');
?><hr />
<h3>Partners Details<?php
echo $form->input('partner_id');
echo $form->input('Partner.name');
echo $form->input('Partner.address1');
echo $form->input('Partner.city');
echo $form->input('Partner.county');
echo $form->input('Partner.postcode');
echo $form->input('city_id');
?><hr />
<h3>Schedule Deal<?php
echo $form->input('start');
echo $form->input('end');
echo $cksource->end();
?>
<?php echo $form->end(__('Submit', true));?>
</div>
Deal Controller
function admin_add() {
if (!empty($this->data['Partner']['name'])) {
$this->data['Deal']['partner_id'] = "";
if ($this->Deal->Partner->saveAll($this->data)) {
$this->Session->setFlash(__('The deal has been saved', true));
$this->redirect(array('controller'=>'deals', 'action' => 'add'));
} else {
$this->Session->setFlash(__('The deal could not be saved. Please, try again.', true));
}
} else {
if ($this->Deal->saveAll($this->data)) {
$this->Session->setFlash(__('The deal has been saved', true));
$this->redirect(array('controller'=>'deals', 'action' => 'add'));
}
}
$partners = $this->Deal->Partner->find('list');
$cities = $this->Deal->City->find('list');
$this->set(compact('partners', 'cities'));
}
Any Ideas guys? If you know a better way to do it would be happy to hear it,
Thanks
Dave
in controller before saving, check if the partner form is not empty, then empty out the $this->data['Deal']['partner_id'];