I'm trying to implement an image upload for my application.
My issues:
- I tried all I could find online, but I am not able to rename the file before uploading. The file name on the server is always a hash or so.
- I think that the thumbnail creation is not working, because I have to add a css to have the image in 120px width.
- When removing one file it is not deleted.
Can anyone please explain how to realise that?
here my sources:
the template:
edit.html.twig
{% extends 'layout.html.twig' %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('includes/dropzone/min/basic.min.css') }}"/>
{% endblock %}
{% block tron %}
<h2>{{component}} edit - {{ entity.monitorId|default(entity.id) }}</h2>
{% endblock %}
{% block body %}
<div class="row">
<div class="col-sm-8">
{{ form_start(form, {'attr': {'id': 'infomonitore_form' } }) }}
{{ form_errors(form) }}
{{ form_row(form.detail) }}
{{ form_row(form.notizen) }}
<div class="form-group row">
<label class="col-form-label col-sm-2">
Files to add:
</label>
<div class="col-sm-10">
<div action="{{ oneup_uploader_endpoint('gallery', {id: entity.id}) }}" class="dropzone js-reference-dropzone" style="min-height: 100px">
</div>
</div>
</div>
<button type="submit" id="buttonSubmit" class="btn btn-primary">Update</button>
Show
{{ form_end(form) }}
</div>
<div class="col-sm-4">
</div>
</div>
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script type="text/javascript" src="{{ asset('js/jquery-3.4.1.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('includes/dropzone/dropzone.js') }}"></script>
<script>
Dropzone.autoDiscover = false;
$(document).ready(function () {
var dropzone = new Dropzone('.js-reference-dropzone', {
autoProcessQueue: false,
dictMaxFilesExceeded: 'Only 5 Image can be uploaded',
acceptedFiles: 'image/*',
maxFilesize: 10, // in Mb
addRemoveLinks: true,
maxFiles: 5,
resizeWidth: 1920,
paramName: 'file',
renameFile: function (file) {
let newName = $('#InfomonitoreFormType_monitorId').val() + '-' + new Date().getTime() + '.' + file.name.split('.').pop();
file.name = newName;
return file.renameFilename = newName;
},
params: {
infomonitor: $('#InfomonitoreFormType_monitorId').val()
},
init: function () {
console.log(this.files);
{% for image in entity.images %}
var mockFile = {name: "{{ image.imageFile }}", size: 12345, dataURL: "{{ asset('locations/')~image.imageFile }}",accepted: true};
this.files.push(mockFile);
this.emit("addedfile", mockFile);
//this.createThumbnailFromUrl(mockFile, mockFile.dataURL);
this.emit("thumbnail", mockFile, mockFile.dataURL)
this.emit("complete", mockFile);
{% endfor %}
this.on("success", function (file, response) {
console.log("Success wurde aufgerufen");
//e.preventDefault();
$('#infomonitore_form').submit();
});
this.on("error", function (tmp) {
console.log('error');
console.log(tmp);
});
}
});
$('#buttonSubmit').click(function(e){
if(dropzone.getQueuedFiles().length > 0) {
e.preventDefault();
dropzone.processQueue();
}
});
});
</script>
{% endblock %}
and here my uploadListener (oneupUploader used):
class UploadListener
{
/* #var EntityManager $manager*/
private $manager;
/* #var InfomonitoreRepository $infomonitor */
private $infomonitor;
/**
* UploadListener constructor.
* #param EntityManager $manager
* #param InfomonitoreRepository $infomonitor
*/
public function __construct(EntityManager $manager, InfomonitoreRepository $infomonitor)
{
$this->manager = $manager;
$this->infomonitor = $infomonitor;
}
public function onUpload(PostPersistEvent $event)
{
$request = $event->getRequest();
/* #var Infomonitore $monitorId */
$monitorId = $this->infomonitor->find($request->get('infomonitor'));
/* #var File $file */
$file = $event->getFile();
$fileName = $monitorId->getMonitorId().'-'.time().'.'.$file->guessExtension();
$image = new Image();
$image->setImageFile(basename($file));
$image->setImageName($fileName);
$image->setInfomonitor($monitorId);
try {
$this->manager->persist($image);
$this->manager->flush();
} catch (ORMException $e) {
print_r($e);
}
// if everything went fine
$response = $event->getResponse();
$response['success'] = true;
return $response;
}
}
Thanks in advance.
you should use a custom namer in oneupuploaderbundle mapping configuration
Related
I am new at Symfony.
I have 2 entities Position and Candidat with relationship as in a position we can have multiple candidats.
Now I have a dropdown populate by positions and below a table with a list of candidat.
I want filter list of candidat when I select a position using the dropdown.
below the codes:
Controller
/**
* #Route(name="filter",path="/filter")
* #param Request $request
*/
public function test2Action(Request $request)
{
$em = $this->getDoctrine()->getManager();
$positions = $em->getRepository('AppBundle:Position')->findAll();
$candidats = $em->getRepository('AppBundle:Candidat')->findAll();
if($request->request->get('myselect')){
$val = $request->request->get('myselect');
$candidats = $em->getRepository('AppBundle:Candidat')->find($val);
return $this->render('postionsearch.html.twig',
array( 'candidats' => $candidats , 'positions' => $positions ) );
}
return $this->render('postionsearch.html.twig',
array( 'candidats' => $candidats , 'positions' => $positions ) );
}
twig:
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<select name="position" id="selectpos">
<option ></option>
{% for position in positions %}
<option value="{{ position.id }}">{{ position.titre }}
</option>
{% endfor %}
</select>
</div>
</div>
</div>
</body>
<div id="ajax-results">Results : </div>
{% if candidats is defined %}
<table id="dataTable">
<tbody>
{% for candidat in candidats %}
<tr>
<td>{{candidat.id}}</td>
<td>{{candidat.nom}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
JS:
<link rel="stylesheet" href="{{
asset('assets/bootstrap/css/bootstrap.min.css') }}" />
<script src="{{ asset('assets/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('assets/bootstrap/js/bootstrap.min.js') }}"></script>
<script>
$(document).ready(function(){
console.log("jQuery is ready");
$("#selectpos").change(function(){
var value= $( "#selectpos option:selected" ).val();
$.ajax({
url:'{{ (path('filter')) }}',
type: "POST",
dataType: "json",
data: {
"myselect": value
},
async: true,
success: function (data)
{
console.log(data)
$('#ajax-results').html(data.output);
},
error: function (err)
{
console.log(err.statusText);
}
});
return false;
})
});
</script>
You need to pass filter parameter to your action:
/**
* #Route(name="filter",path="/filter/{positionId}")
* #param Request $request
*/
Or do it via get:
$request->get('positionId')
And then use it as a criteria in your repository:
$positions = $em->getRepository('AppBundle:Position')->findBy([
'positionId' => $positionId
]);
Ajax request:
$.ajax({
url:'path_to_your_controller',
data: {
"myselect": value
})
I'm working with Easy Admin Bundle for Symfony2. How can I use my own modal dialog with text input for the custom action in the list?
Let's say custom action is called rename and after hitting button Rename in the list I wanna in modal dialog write a new name of something. Then after hitting button OK I wanna call ranameAction in the controller which will do everything needed, but parameter called name must be sent there.
I have the solution but it is not good, there must be some better way.
I created _simple_form.html.twig:
{{
form(rename_form, {
action: rename_form.vars.action ~ '&referer=' ~ referer,
method: 'POST',
attr: { id: 'rename-form', style: 'display: none' }
})
}}
<div id="modal-rename" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<h4>{{ 'rename_modal.title'|trans(_trans_parameters, 'EasyAdminBundle') }}</h4>
<p>{{ 'rename_modal.content'|trans(_trans_parameters, 'EasyAdminBundle') }}</p>
<br />
<input class="form-control" type="text" />
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn">
{{ 'action.cancel'|trans(_trans_parameters, _translation_domain) }}
</button>
{% if easyadmin_action_is_enabled(view, 'rename', _entity_config.name) %}
{% set _rename_action = easyadmin_get_action(view, 'rename', _entity_config.name) %}
<button type="button" data-dismiss="modal" class="btn btn-danger" id="modal-rename-button" formtarget="{{ _rename_action.target }}">
{% if _rename_action.icon %}<i class="fa fa-{{ _rename_action.icon }}"></i>{% endif %}
{{ 'rename_modal.action'|trans(_trans_parameters, 'EasyAdminBundle') }}
</button>
{% endif %}
</div>
</div>
</div>
</div>
In config.yml is a new option:
list:
actions:
rename: { name: rename, type: method, label: 'Rename', css_class: 'btn btn-primary', icon: pencil }
In list.html.twig which I'm using:
{% block main %}
{% block rename_form %}
{% set referer = paginator.currentPage == paginator.nbPages and 1 != paginator.currentPage and 1 == paginator.currentPageResults.count
? path('easyadmin', app.request.query|merge({ page: app.request.query.get('page') - 1 }))
: app.request.requestUri
%}
{{ include('#EasyAdmin/default/includes/_simple_form.html.twig', {
view: 'list',
referer: referer|url_encode,
rename_form: rename_form_template,
_translation_domain: _entity_config.translation_domain,
_trans_parameters: _trans_parameters,
_entity_config: _entity_config,
}, with_context = false) }}
{% endblock rename_form %}
{% endblock %}
{% block body_javascript %}
{{ parent() }}
<script type="text/javascript">
$(function() {
$('#modal-rename-button').on('click', function(e) {
e.preventDefault();
var name = $('#name').val();
var renameForm = $('#rename-form');
renameForm.attr('action', renameForm.attr('action').replace('__name__', name));
});
$('a.action-rename').on('click', function(e) {
e.preventDefault();
var id = $(this).parents('tr').first().data('id');
$('#modal-rename').modal({ backdrop: true, keyboard: true })
.off('click', '#modal-rename-button')
.on('click', '#modal-rename-button', function () {
var renameForm = $('#rename-form');
renameForm.attr('action', renameForm.attr('action').replace('__id__', id));
renameForm.trigger('submit');
});
});
});
</script>
{% endblock %}
And finally controller:
protected function createRenameForm($entityName, $entityId, $name)
{
$formBuilder = $this->get('form.factory')->createNamedBuilder('rename_form')
->setAction($this->generateUrl('easyadmin', array('action' => 'rename', 'entity' => $entityName, 'id' => $entityId, 'name' => $name)))
->setMethod('POST')
;
$formBuilder->add('submit', LegacyFormHelper::getType('submit'), array('label' => 'rename_modal.action', 'translation_domain' => 'EasyAdminBundle'));
$formBuilder->add('_easyadmin_rename_flag', LegacyFormHelper::getType('hidden'), array('data' => '1'));
return $formBuilder->getForm();
}
public function listAction() {
$this->dispatch(EasyAdminEvents::PRE_LIST);
$fields = $this->entity['list']['fields'];
$paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->config['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
$this->dispatch(EasyAdminEvents::POST_LIST, array('paginator' => $paginator));
return $this->render($this->entity['templates']['list'], array(
'title' => 'Branches',
'entity' => $this->entity['name'],
'currentBranch' => $this->repo->getCurrentBranchName(),
'paginator' => $paginator,
'fields' => $fields,
'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
'rename_form_template' => $this->createRenameForm($this->entity['name'], '__id__', '__name__')->createView(),
));
}
I had a similar issue because I wanted to show a modal before to perform a custom action. So what I did was modify the button action with jquery
$(document).ready(function () {
var $archiveButton = $('a.action-archive');
$archiveButton.attr('href', '#');
$archiveButton.attr('data-toggle', 'modal');
$archiveButton.attr('data-target', '#archive-modal');
$archiveButton.attr('data-url', '/url/to/load/form/inside/modal/body');
});
I don't know if it is the better way, but it helped me to show some info to the user before execute the archiveAction() in the AdminController
EDITED: a way to access POST variables
You can access to POST variables through the Container
public function renameAction()
{
$name = $this->container->get('request')->get('your variable');
var_dump($name);
die();
return $this->redirectToRoute('admin', ['entity' => 'Branch', 'action' => 'list']);
}
Play a while with the $this->container->get('request') to find what you are looking for
I have the following ajax I call:
$('.checkbox').click(function () {
$.ajax({
type:'POST',
url: '/loadProducts',
data: {},
success: function(response) {
$('.js-products').html(response);
}});
return false;
});
Now when I call my endpoint loadProducts, I wants to get products, render a product template(s) and return all of them.
In my endpoint I could do this:
/**
* #Route("/loadProducts", name="loadProducts")
*/
public function loadProducts() {
/* #var \AppBundle\Service\ProductService $productService */
$productService = $this->get('app.product');
$products = $productService->getProducts();
$productItems = [];
foreach ($products as $product) {
$productItems = $this->render('home/productItem.html.twig', [
'product' => $product
]);
}
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($productItems));
return $response;
}
But that only renders one product. How could I return rendering multiple product.html.twig files? (apart from creating a new template that renders all)
You will get something like this. Your action will start to render products.html.twig which have a loop that renders multiple times product.html.twig
products.html.twig
{% extends base_template %}
{% block body %}
<div class="container">
<div class="row">
{% for product in products %}
<div class="col-md-3">
{% include 'shop/product.html.twig' %}
</div>
{% endfor %}
</div>
</div>
{% endblock %}
product.html.twig
<div class="product">
<img src="somesource.jpg">
<div class="description">
<h3>{{ product.name }}</h3>
<p>{{ product.description }}</p>
</div>
</div>
In my page show.html.twig i have this block
<div class="col-md-9 col-sm-9 user-wrapper">
<div class="description">
{{ render(controller('FLYBookingsBundle:Post:new')) }}
</div>
</div>
As you can see there is a render that render the page new.html.twig, i want to render the page product << {{ render(controller('FLYBookingsBundle:Post:product')) }} >> in the div description only if the user click on the link My Product List . how do i do that with twig ?
Here is the solution I used to "pop-up" a form for sending an e-mail to an entity based on a button appearing with that entity.
You will need to install jquery if not already installed. There are many possible ways to do this. Use your pal Google & "symfony install jquery" to find one. You may also want to find a good javascript debugger for your browser. I use the Firebug add-on in Firefox.
Template with link (edited for brevity). The returned e-mail form appears in <div id="dialog"></div>:
<div id="dialog"></div>
{% for opp in opportunities %}
<div class="row">
<div class="col-md-9">
<ul class="list-unstyled">
...
<li><a href="#" value="{{ opp.id }}" id="emailOrganization" class="btn btn-xs btn-info" >E-mail {{ opp.orgName }}</a>
</ul>
</div>
</div>
{% endfor %}
Javascript:
$(document).on("click", "#emailOrganization", function () {
var where = $(location).attr('pathname');
var id = $(this).attr("value");
//replaces URI ending in 'search' with 'oppForm/' + id (of organization)
var url = where.replace('search', 'oppForm/' + id);
$.get(url, function (data) {
//creates dialog box containing e-mail form
$('#dialog').dialog();
$('#dialog').dialog({
modal: true,
buttons: [
{
text: "Send",
id: "send",
class: "btn-xs btn-primary",
click: function () {
var formData = $("form").serialize();
$.post(url, formData, function (response) {
if (response.indexOf("Email sent") >= 0) {
$("#send").hide();
}
$('#dialog').html(response);
})
}
},
{
text: 'Close',
id: "close",
class: "btn-xs btn-primary",
click: function () {
$(this).dialog("close");
}
}
],
resizable: true,
});
$('#dialog').dialog("widget").find(".ui-dialog-titlebar").hide();
$('#dialog').html(data);
});
});
Controller (edited for brevity)
/**
* #Route("/oppForm/{id}", name="opp_form")
* #Template("default/oppEmail.html.twig")
*/
public function oppFormAction(Request $request, $id)
{
...
$form = $this->createForm(new OpportunityEmailType($oppName, $orgName, $email, $id));
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isValid()) {
...
}
$response = new Response("Email sent: " . count($to));
return $response;
}
}
return [
'form' => $form->createView(),
'id' => $id,
];
}
Template:
<form role="form" action="{{ path('opp_form', {'id': id}) }}" method="post" name="opp_email">
{# hidden submit button allows functional test; also tested with codeception #}
<div style="visibility: hidden;"><input type="submit" value="Mail"></div>
{{ form_widget(form._token) }}
{{ form_row(form.id) }}
{{ form_row(form.to) }}
{{ form_row(form.from) }}
{{ form_row(form.subject) }}
{{ form_row(form.message) }}
</form>
I'm trying to add a field name to my register page , i'm using fosuserbundle. But i got this error:
Variable "name" does not exist in FOSUserBundle:Registration:register_content.html.twig at line 55
Thank you
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
fos_user:
db_driver: orm
firewall_name: main
user_class: FLY\UserBundle\Entity\User
use_listener: true
#use_flash_notifications: true
use_username_form_type: true
model_manager_name: null # change it to the name of your entity/document manager if you don't want to use the default one.
from_email:
address: xxxxxxx#hotmail.fr
sender_name: webmaster
profile:
form:
type: fos_user_profile
name: fos_user_profile_form
validation_groups: [Profile, Default]
change_password:
form:
type: fos_user_change_password
name: fos_user_change_password_form
validation_groups: [ChangePassword, Default]
registration:
confirmation:
from_email: # Use this node only if you don't want the global email address for the confirmation email
address: xxxxxx#hotmail.fr
sender_name: Webmaster
enabled: true # change to true for required email confirmation
template: FOSUserBundle:Registration:email.txt.twig
form:
type: fos_user_registration
name: fos_user_registration_form
validation_groups: [Registration, Default]
resetting:
token_ttl: 86400
email:
from_email: # Use this node only if you don't want the global email address for the resetting email
address: ...
sender_name: ...
template: FOSUserBundle:Resetting:email.txt.twig
form:
type: fos_user_resetting
name: fos_user_resetting_form
validation_groups: [ResetPassword, Default]
service:
mailer: fos_user.mailer.default
email_canonicalizer: fos_user.util.canonicalizer.default
username_canonicalizer: fos_user.util.canonicalizer.default
token_generator: fos_user.util.token_generator.default
user_manager: fos_user.user_manager.default
#group:
#group_class: ~ # Required when using groups
#group_manager: fos_user.group_manager.default
#form:
#type: fos_user_group
#name: fos_user_group_form
#validation_groups: [Registration, Default]
register_content.html.twig
{% extends "::base.html.twig" %}
{% trans_default_domain 'FOSUserBundle' %}
{% block header %}
{% endblock header %}
{% block content %}
<section id="headlogin" xmlns="http://www.w3.org/1999/html">
<div class="container">
<div class="row">
<div class="btn pull-right">
<br/>
<a href="{{ path('fos_user_security_login') }}" class="btn btn-border-purple-light nl-btn">
{% trans %}Log in{% endtrans %}
</a></div></div>
<div class="row">
<h1 class="leadlogin">AWESOME, CUSTOMIZABLE, FREE</h1>
<p class="taglinelogin">PROGRESSUS: free business bootstrap template by Template</p>
<div class="col-lg-12 col-md-4 centeredlogin">
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
{% if is_granted('IS_AUTHENTICATED_FULLY') %}
Hello {{ app.user.username }}
Logout
{% else %}
{{ render(url('hwi_oauth_connect')) }}
{% endif %}
<button class="form-control btn btn-blue">
<i class="icon ion-social-facebook"></i>
{% trans %}Log in with facebook{% endtrans %}
Sign in with Facebook
</button>
</div>
</div>
</div>
<hr>
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
{{ form_widget(name) }}
<div style="margin-bottom:1px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
{{ form_widget(form.username, { 'attr': {'class': 'form-control', 'placeholder': 'form.username'|trans } }) }}
{{ form_errors(form.username) }}
</div></div>
<div class="form-group">
<div style="margin-bottom: 1px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
{{ form_widget(form.email, { 'attr': {'class': 'form-control', 'placeholder': 'form.email'|trans } }) }}
{{ form_errors(form.email) }}
</div></div>
<div class="form-group">
<div style="margin-bottom: 1px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
{{ form_widget(form.plainPassword.first, { 'attr': {'class': 'form-control', 'placeholder': 'form.password'|trans } }) }}
{{ form_errors(form.plainPassword.first) }}
{{ form_widget(form.plainPassword.second, { 'attr': {'class': 'form-control', 'placeholder': 'form.password_confirmation'|trans } }) }}
{{ form_errors(form.plainPassword.second) }}
{{ form_rest(form) }}
</div></div>
{{ form_rest(form) }}
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<button type="submit" id="_submit" name="_submit" class="form-control btn btn-whitered">
<i class="icon ion-log-in"></i>
{{ 'registration.submit'|trans }}
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div></div>
<div id="fb-root"></div>
{% render(controller('HWIOAuthBundle:Connect:connect')) %}
</div>
</section>
{% endblock content %}
{% block foot_script %}
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '708572945914167', // App ID from the app dashboard
//channelUrl : '//yourdomain.com/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function fb_login() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
alert('Already connected, redirect to login page to create token.');
document.location = "{{ url("hwi_oauth_service_redirect", {service: "facebook"}) }}";
} else {
// not_authorized
FB.login(function(response) {
if (response.authResponse) {
document.location = "{{ url("hwi_oauth_service_redirect", {service: "facebook"}) }}";
} else {
alert('Cancelled.');
}
}, {scope: 'email'});
}
});
}
</script>
<h1 class="title">Hello {{ name }}!</h1>
Hello resource secured for <strong>admin</strong> only.
<p>
Facebook Connect Button (Dialog)
</p>
{# Bonus: Show all available login link in HWIOAuthBundle #}
{% render(controller('HWIOAuthBundle:Connect:connect')) %}
{% endblock foot_script %}
{% block footer %} {% endblock footer %}
services.yml
**parameters:
hwi_oauth.user.provider.class: FLY\UserBundle\Security\Core\User\FOSUBUserProvider
services:
hwi_oauth.user.provider:
class: hwi_oauth.user.provider.class
#this is the place where the properties are passed to the UserProvider - see config.yml
arguments: [#fos_user.user_manager,{facebook: facebook_id,}]
boutique_user.registration.form.type:
class: FLY\Form\MyRegistrationFormType
arguments: [%fos_user.model.user.class%]
tags:
- { name: form.type, alias: boutique_user.registration.form.type: }**
MyRegistrationFormType.php
<?php
namespace FLY\UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use FOS\UserBundle\Form\RegistrationFormType as BaseType;
class MyRegistrationFormType extends BaseType
{
private $class;
/**
* #param string $class The User class name
*/
public function __construct($class)
{
parent::__construct($class);
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm(builder,$options);
$builder
->add('name', 'text')
;
}
public function getName()
{
return 'boutique_user_registration';
}}
RegistrationForm.php
<?php
/*
* This file is part of the FOSUserBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationFormType extends AbstractType
{
private $class;
/**
* #param string $class The User class name
*/
public function __construct($class)
{
$this->class = $class;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => $this->class,
'intention' => 'registration',
));
}
// BC for SF < 2.7
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$this->configureOptions($resolver);
}
public function getName()
{
return 'fos_user_registration';
}
}
FOSUserProvider.php
**<?php
/*
* This file is part of the HWIOAuthBundle package.
*
* (c) Hardware.Info <opensource#hardware.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FLY\Bundle\UserBundle\Security\Core\User;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
use Symfony\Component\Security\Core\User\UserInterface;
class FOSUBUserProvider extends BaseClass
{
/**
* {#inheritDoc}
*/
public function connect(UserInterface $user, UserResponseInterface $response)
{
$property = $this->getProperty($response);
$username = $response->getUsername();
//on connect - get the access token and the user ID
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
//we "disconnect" previously connected users
if (null !== $previousUser = $this->userManager->findUserBy(array($property => $username))) {
$previousUser->$setter_id(null);
$previousUser->$setter_token(null);
$this->userManager->updateUser($previousUser);
}
//we connect current user
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
$this->userManager->updateUser($user);
}
/**
* {#inheritdoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$username = $response->getUsername();
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
//when the user is registrating
if (null === $user) {
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
// create new user here
$user = $this->userManager->createUser();
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
//I have set all requested data with the user's username
//modify here with relevant data
$user->setUsername($username);
$user->setEmail($username);
$user->setPassword($username);
$user->setEnabled(true);
$this->userManager->updateUser($user);
return $user;
}
//if user exists - go with the HWIOAuth way
$user = parent::loadUserByOAuthUserResponse($response);
$serviceName = $response->getResourceOwner()->getName();
$setter = 'set' . ucfirst($serviceName) . 'AccessToken';
//update access token
$user->$setter($response->getAccessToken());
return $user;
}
}**
{{ form_widget(**form**.name) }}