I have created a form for an entity Event with user's fields like "email" and "password" what I use to create a user manually in the controller.
I can create the event and the user without problems, but I need to send a confirmation mail to enable the user. I can do it from the normal registration form, but here I don't know how to do it.
Sorry if my english isn't very good. I'm learning it.
The controller:
class EventController extends Controller
{
public function ajaxAction(Request $request) {
if (! $request->isXmlHttpRequest()) {
throw new NotFoundHttpException();
}
// Get the province ID
$id = $request->query->get('category_id');
$result = array();
// Return a list of cities, based on the selected province
$repo = $this->getDoctrine()->getManager()->getRepository('CASEventBundle:Subcategory');
$subcategories = $repo->findByCategory($id, array('category' => 'asc'));
foreach ($subcategories as $subcategory) {
$result[$subcategory->getName()] = $subcategory->getId();
}
return new JsonResponse($result);
}
public function indexAction(Request $request) {
$lead = new Lead();
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
if(is_object($user)) {
$promotor = $em->getRepository('CASUsuariosBundle:Promotor')->find($user);
if (is_object($promotor)) {
$form = $this->createForm(new EventType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:event.html.twig";
$isPromotor = true;
}
} else {
$form = $this->createForm(new LeadType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:full_lead.html.twig";
$isPromotor = false;
}
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
if($isPromotor === true) {
$type = $promotor->getType();
$name = $user->getName();
$lastname = $user->getLastName();
$email = $user->getEmail();
$password = $user->getPassword();
$phone = $user->getPhone();
$company = $promotor->getCompany();
$lead->setEventType($type);
$lead->setPromotorName($name);
$lead->setPromotorLastName($lastname);
$lead->setPromotorEmail($email);
$lead->setPromotorPhone($phone);
$lead->setPromotorCompany($company);
}
$emailReg = $form->get('promotorEmail')->getData();
$passwordReg = $form->get('promotorPassword')->getData();
$nameReg = $form->get('promotorName')->getData();
$typeReg = $form->get('promotorType')->getData();
$lastnameReg = $form->get('promotorLastName')->getData();
$phoneReg = $form->get('promotorPhone')->getData();
$companyReg = $form->get('promotorCompany')->getData();
if(!empty($emailReg) && !empty($passwordReg)) {
$userManager = $this->get('fos_user.user_manager');
$newUser = $userManager->createUser();
$newPromotor = new Promotor();
$newUser->setUsername($emailReg);
$newUser->setEmail($emailReg);
$newUser->setName($nameReg);
$newUser->setLastname($lastnameReg);
$newUser->setPhone($phoneReg);
$newUser->setIsPromotor(true);
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($newUser, strval($passwordReg));
$newUser->setPassword($encoded);
$userManager->updateUser($newUser);
$newPromotor->setType($typeReg);
$newPromotor->setCompany($companyReg);
$newPromotor->setIdPromotor($newUser);
$em->persist($newUser);
$em->persist($newPromotor);
$em->persist($lead);
$em->flush();
//return $response;
}
$em->persist($lead);
$em->flush();
return $this->redirect($this->generateUrl('CASEventBundle_create'));
}
}
return $this->render($template, array('form' => $form->createView()));
}
}
you could just create a confirmation token yourself and set it to the not yet active user, send him a mail using swift wich contains a link to confirm like :
$confiToken = "123";
$url="http://url.com/confirm/$confiToken";
$user->setConfirmationToken($confiToken);
$message = $mailer->createMessage()
->setSubject('Confirm registration')
->setFrom('from#mail.com')
->setTo($sendTo)
->setBody(
$this->renderView(
'Bundle:Email:confirm.html.twig',
array(
'headline' => "Confirm your registration",
"sendTo"=>$sendTo,
"name"=>false,
"date"=>$date,
"message"=>"here ist your confirmationlink ".$url." "
)
),
'text/html'
);
$mailer->send($message);
when the user clicks the link in the email you can manually generate the token and set the user active:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
...
$user=$em->getRepository("Bundle:User")->findOneByConfirmationToken($token);
if(!$user || $user->isEnabled()){
throw $this->createNotFoundException("link out of date");
}else {
$user->setEnabled(true);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.context')->setToken($token);
$this->get('session')->set('_security_main',serialize($token));
$em->flush();
return $this->redirect($this->generateUrl('core_customer_dashboard'));
}
Related
I have a setup where for one of the Model I have repeat fields like user and userchildren
so userchildren have a set of fields like child_name, child_birth_date and child_gender
My controller code is like this:
public function actionUpdateProfile()
{
$user_id = Yii::$app->user->identity->id;
$model = User::find()->where(['id' => $user_id])->one();
$UserProfile = UserProfile::find()->where(['user_id' => $model->id])->one();
$userbillinginfo = UserBillingInfo::find()->where(['user_id' => $model->id])->one();
$userchildren = UserChildren::find()->where(['user_id' => $model->id])->all();
if ($userchildren) {
$profile = $UserProfile;
$billinginfo = $userbillinginfo;
$userchild = $userchildren;
} else {
$profile = new UserProfile;
$profile->user_id = $model->id;
$billinginfo = new UserBillingInfo;
$billinginfo->user_id = $model->id;
$userchild = New UserChildren;
$userchild->user_id = $model->id;
}
if (Yii::$app->request->isAjax && $model->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}
if (Yii::$app->request->isAjax && $profile->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($profile);
}
if (Yii::$app->request->isAjax && $billinginfo->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($billinginfo);
}
if (Yii::$app->request->isAjax && $userchild->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($userchild);
}
if ($model->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && $billinginfo->load(Yii::$app->request->post())) {
$model->username = $model->email;
$model->save();
$profile->save();
$billinginfo->save();
if (!empty($_POST['UserChildren']) && !is_null($_POST['UserChildren'])) {
foreach ($_POST['UserChildren'] as $rows) {
$userchild = New UserChildren;
$userchild->attributes = $rows;
$userchild->user_id = $model->id;
$userchild->save();
}
}
return $this->redirect(['view']);
} else {
return $this->render('update-profile', [
'model' => $model,
'profile' => $profile,
'billinginfo' => $billinginfo,
'userchild' => $userchild,
]);
}
}
I am facing two issues:
first, when I go for an update of the profile the data is shown properly in the form, I can add records without any issue to the Model UserChildren
But if I edit an existing record it is inserting this as a new record, whereas I expect this to be updated.
I had this line of code like below:
,
if ($model->load(Yii::$app->request->post()) and
$profile->load(Yii::$app->request->post()) and
$billinginfo->load(Yii::$app->request->post()) and
$billinginfo->load(Yii::$app->request->post())
) {
...
but after I updated the line of code,
$userchildren = UserChildren::find()->where(['user_id' => $model->id])->one();
to
$userchildren = UserChildren::find()->where(['user_id' => $model->id])->all();
and thus had to modify the line like below:
if ($model->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && $billinginfo->load(Yii::$app->request->post()) ) {
What I am missing here? Thanks.
I have {{ knp_pagination_render(pagination1) }} on view InfCustumersBundle:Faktura:indexoryginal.html.twig
This code show me paginarion:
public function indexoryginalAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$req = $em->getRepository('...:Faktura');
$qb = $req->createQueryBuilder('p');
$search = $qb
.
.
->getQuery();
$form = $this->createFormBuilder()
.
.
->getForm();
$paginator = $this->get('knp_paginator');
$pagination1 = $paginator->paginate(
$search, $request->query->get('page', 1)/* page number */, 5/* limit per page */
);
return $this->render('InfCustumersBundle:Faktura:indexoryginal.html.twig', array(
'pagination1' => $pagination1,
'form' => $form->createView()
));
and this work fine, but code bellow don't show pagination tags. Only the first 3 items. Where I made a mistake ?
public function indexAction(Request $request, $type = 1) {
$data = array();
$form = $this->createFormBuilder()
.
.
->getForm();
if ($request->isMethod('GET')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$name = ($data['for'] == 'name' ? true : false);
if ($name) {
return $this->Name($form);
}
}
return $this->redirect($this->generateUrl('faktura_oryginal', array(
$this->get('session')->getFlashBag()->add('error', 'error')
)));
}
protected function Name($form) {
$em2 = $this->getDoctrine()->getManager();
$req = $em2->getRepository('InfCustomersBundle:Faktura');
$qb = $req->createQueryBuilder('p');
$query2 = $qb
.
.
->getQuery();
$entities2 = $query2->getResult();
if ($entities2) {
$paginator = $this->get('knp_paginator');
$request = $this->get('request_stack');
// $request = $this->getRequest();
$pagination1 = $paginator->paginate(
$query2, $request->getCurrentRequest()->query->get('page', 1)/* page number */, 3/* limit per page */
);
return $this->render('InfCustumersBundle:Faktura:indexoryginal.html.twig', array(
'pagination1' => $pagination1,
'form' => $form->createView()
));
} else {
return $this->redirect($this->generateUrl('faktura_oryginal', array( $this->get('session')->getFlashBag()->add('error', 'error')
)));
}
}
}
I found a solution
I changed:
$entities2 = $query2->getResult();
if ($entities2) {
to
$pagination1 = $paginator->paginate(
$query2, $request->getCurrentRequest()->query->get('page',1),25);
if (count($pagination1) > 0) {
and now is working well
How can I get the current Post? I'm trying to redirect to my current post where im sending my vote but this method that i created redirects to Oldest Post created by this user.
public function ScoreAction(Request $request){
$em = $this->getDoctrine()->getManager();
$idPoster = $request->request->get('id_posterUser');
$positive= $request->request->get('positive');
$negative= $request->request->get('negative');
$user= $em->getRepository(User::class)->findOneById($idPoster);
$topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());
$score = $usuari->getReputation();
if ($positive!= null) {
$score = $score + 1;
}
if($negative!= null){
$score = $score - 1;
}
$user->setReputation($score );
$em->persist($user);
$em->flush();
$redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));
return $this->redirect($redirect);
}
Edit: Added my Solution.
Solution :
public function ScoreAction(Request $request){
$em = $this->getDoctrine()->getManager();
$idTopic = $request->request->get('id_topic');
$idPoster = $request->request->get('id_poster');
$positive= $request->request->get('positive');
$negative= $request->request->get('negatiu');
$user= $em->getRepository(User::class)->findOneById($idPoster);
$topic = $em->getRepository(Topic::class)->findOneById($idTopic);
$score= $user->getReputation();
if ($positive!= null) {
$score= $score+ 1;
}
if($negative!= null){
$score= $score- 1;
}
$user->setReputation($score);
$em->persist($user);
$em->flush();
$redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));
return $this->redirect($redirect);
}
You are searching topic by user:
$topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());
findOneByUser - builds query WHERE user.id = :user_id LIMIT 1
For get the last Topic you need to add ordering.
$topic = $em->getRepository(Topic::class)->findOneBy(
array('user' => $user),
array('id' => 'desc')
);
I am trying to insert uploaded filenames to a table with the date they were uploaded, but I am running into some errors with trying to get the values of the filename with $_FILES
Here is my code:
public function uploadAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setVariable('user1', $user->username);
$form = new FileUploadForm();
$request = $this->getRequest();
if ($request->isPost()) {
$file = new File();
$form->setInputFilter($file->getInputFilter());
$captions = $request->getPost()->toArray();
$get_file = $this->params()->fromFiles('file');
$data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min' => '10kB', 'max' => FileHandler::FILESIZE . 'MB'));
$extension = new Extension(array('jpg', 'jpeg', 'png'), true);
$adapter = new Http();
$adapter->setValidators(array($size, $extension), $get_file['name']);
if (!$adapter->isValid()) {
return $this->redirect()->toUrl('/admin/upload-failure');
} else {
$dir_check = !is_dir(FileHandler::UPLOAD_PATH . $user->username)
?
mkdir(FileHandler::UPLOAD_PATH . $user->username) ? FileHandler::UPLOAD_PATH . $user->username : null
: FileHandler::UPLOAD_PATH . $user->username;
$adapter->setDestination($dir_check);
if ($adapter->receive($get_file['name'])) {
$this->getFileUploadFactory()->insertUploadDate($_FILES);
$file->exchangeArray($form->getData());
return $this->redirect()->toUrl('/admin/upload-success');
} else {
return $this->redirect()->toUrl('/admin/upload-failure');
}
}
}
}
public function insertUploadDate(array $file)
{
try {
$insert = new Insert('uploads');
foreach ($file as $key => $value) {
$insert->columns(array('filename', 'upload_date'))
->values(array('filename' => $value, 'upload_date' => date('Y-m-d')));
$adapter = $this->table_gateway->getAdapter();
$adapter->query(
$this->sql->getSqlStringForSqlObject($insert),
$adapter::QUERY_MODE_EXECUTE
);
}
return true;
} catch (\PDOException $e) {
// save the exception message to the error file
$writer = new Stream(self::ERROR_PATH);
$logger = new Logger();
$logger->addWriter($writer);
$logger->info($e->getMessage() . "\r\r");
return false;
}
}
and then in the controller I am calling it like this:
$this->getFileUploadFactory()->insertUploadDate($_FILES);
Like I said, it's not inserting the correct names of the files I uploaded (using html5 multiple upload option)
Thanks!
if i update any of this personal details filed then i click on save it. its save the new data and change my login password also to random value
public function update_personal_details() {
$this->layout = null ;
$this->autoRender = false;
$response = array('success' => true);
if ($this->request->isPost()) {
if($this->User->exists($this->Auth->user('id'))) {
try {
$this->User->read(null, $this->Auth->user('id'));
$this->User->set('first_name',$this->request->data["first_name"]);
$this->User->set('last_name',$this->request->data["last_name"]);
$this->User->set('mobile',$this->request->data["mobile"]);
$this->User->set('city',$this->request->data["city"]);
$this->User->save();
} catch (exception $ex) {
$response['success'] = false;
}
}
}
return json_encode($response);
}
To make sure that cakePHP only updates the wanted cols you can pass the data and a field list on the save command:
Model::save(array $data = null, boolean $validate = true, array $fieldList = array())
Just have a look at Cookbook Save your Data
For you this should work:
$data = array();
$data['first_name'] = $this->request->data["first_name"]);
$data['last_name'] = $this->request->data["last_name"]);
$data['mobile'] = $this->request->data["mobile"]);
$data['city'] = $this->request->data["city"]);
$this->User->save(array('User' => $data), true, array('first_name', 'last_name', 'mobile', 'city'));
Hope that helps