Symfony2.1 FosUserBundle translation broken - symfony-2.1

I had a project with Symfony 2.0 and FOSUserBundle 1.2.0, and everything was working fine. When I upgraded to the latest Symfony 2.1 version and the latest FOSUserBundle from the master branch, after fixing lots of stuff, the labels are not being translated, i.e. "form.username".
I had the User Bundle overwritten by a custom bundle I made. I've overwritten the following stuff:
Controller
ChangePasswordController
GroupController
RegistrationController
UserController
Form
Type
ChangePasswordFormType
RegistrationFormType
Resources
config
routing.yml
views
ChangePassword
changePassword_content.html.twig
changePassword.html.twig
Form
form_group.html.twig
form_user.html.twig
Group
edit.html.twig
list.html.twig
new.html.twig
show.html.twig
Registration
checkEmail.html.twig
email.txt.twig
register_content.html.twig
register.html.twig
User
edit.html.twig
index.html.twig
show.html.twig
I also have a custom user and group entity, and my custom UserType and GroupType which I omitted in the previous tree.
The translation files where at app/Resources/translations/FOSUserBundle.en.yml
I also tryed copying them to my bundle, src/Acme/UserBundle/Resources/translations/FOSUserBundle.en.yml
None of them is working with symfony 2.1.
Of course I cleaned the cache, the production cache, and regenerated assets just in case and refreshed the browser... Everything several times and nothing.
I searched here and on Google and I can't find any clues, I tried some things but without success.
I will copy the contents of some of the files below.
Acme/UserBundle/Controller/RegistrationController.php
<?php
namespace Acme\UserBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
class RegistrationController extends BaseController
{
public function registerAction()
{
$form = $this->container->get('fos_user.registration.form');
$formHandler = $this->container->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
$authUser = false;
if ($confirmationEnabled) {
$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
$authUser = true;
$route = 'AcmeUserBundle_admin_user_index';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$url = $this->container->get('router')->generate($route);
$response = new RedirectResponse($url);
if ($authUser) {
$this->authenticateUser($user, $response);
}
return $response;
}
return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
'form' => $form->createView(),
));
}
}
Acme/UserBundle/Form/Type/RegistrationFormType.php
<?php
namespace Acme\UserBundle\Form\Type;
use Doctrine\ORM\EntityManager;
class RegistrationFormType extends BaseType
{
private $entityManager;
public function __construct($class, EntityManager $entityManager)
{
parent::__construct($class);
$this->entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle', 'error_bubbling' => true))
->add('nombre', 'text', array('error_bubbling' => true))
->add('apellido', 'text', array('error_bubbling' => true))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle', 'error_bubbling' => true))
->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',
'error_bubbling' => true,
))
->add('groups', 'entity', array(
'class' => 'Acme\\UserBundle\\Entity\\Group',
'property' => 'name',
'label' => 'Grupos',
'empty_value' => 'Seleccione Grupos',
'multiple' => true,
'expanded' => true,
'required' => false,
));
}
public function getName()
{
return 'acme_user_registration';
}
}
Acme/Resources/views/Registration/register_content.html.twig
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register">
<div class="content no-padding" {{ block('container_attributes') }}>
{{ form_widget(form) }}
</div>
<div class="actions">
<div class="actions-left" style="margin-top: 8px;"></div>
<div class="actions-right">
<input type="submit" value="{{ 'registration.submit'|trans({}, 'FOSUserBundle') }}" />
</div>
</div>
Acme/Resources/views/Registration/register.html.twig
{% extends "AcmeAdminBundle:Base:base_auth.html.twig" %}
{% form_theme form 'AcmeUserBundle:Form:form_user.html.twig' %}
*[...] Here are stylesheets and JS[...]*
{% block main_content %}
<!-- Start of the main content -->
<div id="main_content">
<h2 class="grid_12">{% block title "Crear Usuario" %}</h2>
<div class="clean"></div>
<div class="grid_6">
<div class="box">
<div class="header">
<img src="{{ asset('bundles/acmeadmin/img/icons/packs/fugue/16x16/ui-text-field-format.png') }}" alt="" width="16"
height="16">
<h3>Información Básica</h3>
<span></span>
</div>
{% block fos_user_content %}
{% include "AcmeUserBundle:Registration:register_content.html.twig" %}
{% endblock fos_user_content %}
</div> <!-- End of .box -->
</div> <!-- End of .grid_6 -->
</div> <!-- End of #main_content -->
<div class="push clear"></div>
{% endblock main_content %}
If I disable my bundle, removing
public function getParent()
{
return 'FOSUserBundle';
}
the labels appear translated as expected. I don't know what else to do. Any Suggestions?

Related

How to make flatpickr datepicker reactive in livewire / alpinejs app?

In my laravel 7 /livewire 1.3 / alpinejs 2 project
I added flatpickr datepicker from https://flatpickr.js.org
datepicker works ok, but reactive does not work. In the code below
$current_operation_date - public var in the component and is is modified ok
but alpine var operation_date is not changed when in datepicker value is selected:
<div>
$current_operation_date::{{$current_operation_date}}<BR>
operation_date::<div x-html="operation_date"></div>
<!-- The line above is not modified when in datepicker value is selected -->
<div x-data="{ operation_date: '{{$current_operation_date}}'}">
<input
type='text'
id="flatpickr_operation_date"
wire:model.lazy="current_operation_date"
x-model="operation_date"
x-on:blur="$dispatch('input', operation_date)"
class="form-control editable_field"
/>
</div>
</div>
#section('scripts')
<script>
$(document).ready(function(){
var fp = flatpickr(document.querySelector('#flatpickr_operation_date'), {
enableTime: false,
dateFormat: 'Y-m-d',
altFormat: "F j, Y",
altInput: true,
inline: false,
locale: "es",
"minDate": "2020-7-12",
"maxDate": "2020-9-12",
defaultDate: ["2020-9-10"],
onChange: function(selectedDates, dateStr, instance) {
console.log('selectedDates::')
console.log(selectedDates) //valid
console.log('date: ', dateStr);
}
});
});
</script>
#endsection
<style>
...
If there is a way to make it reactive ?
Thanks!
Using the TALL stack with Livewire 2.7, alpine 3.4 and Laravel 8
This is my current solution
components/inputs/date.blade.php
#props(['options' => []])
#php
$options = array_merge([
'dateFormat' => 'Y-m-d',
'enableTime' => false,
'altFormat' => 'j F Y',
'altInput' => true
], $options);
#endphp
<div wire:ignore>
<input
x-data="{
init() {
flatpickr(this.$refs.input, {{json_encode((object)$options)}});
}
}"
x-ref="input"
type="text"
{{ $attributes->merge(['class' => 'form-input w-full rounded-md shadow-sm']) }}
/>
</div>
Then I'm using it like this:
<x-inputs.date id="flatpickr_operation_date" wire:model="current_operation_date" />
bidirectional
To go deeper, when we want to dynamically change the date from the Livewire component and we want the date to be updated in flatpickr as well, here's my current solution
here's my current solution
#props(['options' => []])
#php
$options = array_merge([
'dateFormat' => 'Y-m-d',
'enableTime' => false,
'altFormat' => 'j F Y',
'altInput' => true
], $options);
#endphp
<div wire:ignore>
<input
x-data="{
value: #entangle($attributes->wire('model')),
instance: undefined,
init() {
$watch('value', value => this.instance.setDate(value, false));
this.instance = flatpickr(this.$refs.input, {{ json_encode((object)$options) }});
}
}"
x-ref="input"
x-bind:value="value"
type="text"
{{ $attributes->merge(['class' => 'form-input w-full rounded-md shadow-sm']) }}
/>
</div>

how to add specific comment to post in django post

I have posts that, user can add comments to, but i unable to add those comments to that specific posts, here is the code that I'm following:-
the code is working fine with models and the only issue is when comment added, its added to only one post, rather than specific comment to specific post
HTML Code
<div class="quote-comment-box">
<form method="POST" class="com">
{% csrf_token %}
<input placeholder="Your thought" type="text" name="quote-comment" class="comment-input" id="{{ quote.id }}" title="{{ quote.user.id }}" data="{{ request.user }}">
<button type="submit" href="{% url 'micro__blog:quote_comment' %}" class="comment-button">POST</button>
</form>
<div class="content" id="content">
</div>
</div>
js code
$('.comment-button').click(function (params) {
csrftoken()
var index = $('.comment-button').index(this)
var comment = $( ".comment-input" ).eq(index).val()
var id = $( ".content" ).eq(index).attr('id')
params.preventDefault()
$.ajax({
url:$(this).attr("href"),
data:{
'blog_id' : $( '.comment-input' ).eq(index).attr('id'),
'blog_user' : $( '.comment-input' ).eq(index).attr('title'),
'comment' : $( ".comment-input" ).eq(index).val(),
},
type:'POST',
dataType: 'json',
success: function (res, status) {
if (res['status'] == 'ok') {
$('.comment-input').eq(index).val('');
var content = $('.content').eq(index)
console.log(index, content)
const div = document.createElement('div');
div.className = "comment-added"
div.innerHTML = `
<span class="user">` + $( ".comment-input" ).eq(index).attr('data') + `</span>
<span class="text">` + comment + `</span>`;
document.getElementById('content').appendChild(div);
console.log(res.status)
} else {
console.log(res.status)
}
},
error: function (res) {
console.log(res.status);
}
})
Here is view code
def quote_comment(request):
if request.method == 'POST':
blog_id = request.POST.get('blog_id')
blog_user = request.POST.get('blog_user')
comment = request.POST.get('comment')
current_user = User.objects.get(id = request.user.id)
if blog_id and blog_user and comment and current_user:
blog_id = Quote.objects.get(id = blog_id)
blog_user = User.objects.get(id=blog_user)
try:
QuoteComment.objects.get_or_create(user=current_user,blog_id=blog_id,blog_user_id=blog_user,comment=comment)
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'error'})
return JsonResponse({'status':'error'})
and url
path('quote_comment/', views.quote_comment, name="quote_comment"),
A view that renders this template
def index(request):
quotes= Quote.objects.all()
return render(request=request, template_name="dashboard.html",context={'quotes':quotes})
to render on quotes im suing for loop like this
{% for quote in quotes %}
{% endfor %}

Blaze LoginButtons Template Rendered in React - Login Only Works on Homepage

So I am using Meteor/React, but I used Blaze's login template for its convenience. It works great on the homepage, but when I try to login from any other page on the site, the page reloads and the login appears to have been unsuccessful.
This is my implementation.
AccountsUI.jsx
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
export class AccountsUI extends React.Component {
componentDidMount(){
this.view = Blaze.render(Template.loginButtons, this.refs.loginContainer);
}
componentWillUnmount(){
Blaze.remove(this.view);
}
render(){
return(
<span ref="loginContainer" />
)
}
}
mainLayout.jsx
<div className="container-fluid">
<a className="navbar-btn pull-left panel-body"><b>FAQ</b></a>
<a className="navbar-btn pull-right panel-body"><b>Category</b></a>
<a className="navbar-btn pull-right panel-body"><b>Notifications</b></a>
<a className="navbar-btn pull-right panel-body"><b><AccountsUI /></b></a>
</div>
</div>
Why would this work only on certain pages?
Blaze
Your code looks ok, are you importing all components correctly?
Try: https://atmospherejs.com/gadicc/blaze-react-component
and do:
import Blaze from 'meteor/gadicc:blaze-react-component';
....
<a className="navbar-btn pull-right panel-body"><b><Blaze template="loginButtons" /></b></a>
....
Without trying to change your choice of tools too much, I have been exploring React, Meteor and Authentication for a little while, often getting stuck in state management and other dark holes. Below is a overview of some options:
React Accounts-UI package
Personally as a quick tool I am a big fan of the React Accounts-UI package https://atmospherejs.com/std/accounts-ui
It's easy to implement and has many React specific config options.
Check out 'Create your own styled version' to implement in Navbar at https://github.com/studiointeract/accounts-ui/blob/master/README.md
React with Kadira FlowRouter and ReactLayout
For something within the Navbar, here is a stab with flow router.
From the Meteor Guide User/Authentication section:
While a router is optional and the basic functionality will work without it, it’s also a good idea to pick a router integration:
For Navbar login (Not React Accounts-UI).
You need Flowrouter and Reactlayout
Routes
We create 2 route groups which allow us to build auth logic into Flow router easily:
const publicRoutes = FlowRouter.group( { name: 'public' } );
publicRoutes.route( '/login', {
name: 'login',
action() {
ReactLayout.render( App, {
yield: <Login /> }
);
}
}
);
const authenticatedRoutes = FlowRouter.group( { name: 'authenticated' } );
authenticatedRoutes.route( '/hidden', {
name: 'hidden',
action() {
ReactLayout.render( App, {
yield: <Hidden /> }
);
}
}
);
App:
You can modify this to suit your own setup. The approach here is to grab the reactmeteordata mixing which allows us to test if the user is logged or logging in. The isPublic function allows us to test if the user should be allowed on the current route. The rest should be self explanatory.
App = React.createClass({
mixins: [ ReactMeteorData ],
getMeteorData() {
return {
loggingIn: Meteor.loggingIn(),
hasUser: !!Meteor.user(),
isPublic( route ) {
let publicRoutes = [
'login'
];
return publicRoutes.indexOf( route ) > -1;
},
canView() {
return this.isPublic( FlowRouter.current().route.name ) || !!Meteor.user();
}
};
},
loading() {
return <div className="loading"></div>;
},
getView() {
return this.data.canView() ? this.props.yield : <Login />;
},
render() {
return <div className="app-root">
<AppHeader hasUser={this.data.hasUser} />
<div className="container">
{this.data.loggingIn ? this.loading() : this.getView()}
</div>
</div>;
}
}
);
Header:
Nothing cosmic, we change the brandLink depending on user state. We then check hasUser (passed as a prop from the App component) to change which nav component to display.
AppHeader = React.createClass({
mixins: [ ReactMeteorData ],
getMeteorData() {
return { brandLink: !!Meteor.user() ? '/hidden' : '/login' }; },
render() {
return ( <nav className="navbar navbar-default" role="navigation">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"><span className="sr-only">Toggle navigation</span><span className="icon-bar"></span> <span className="icon-bar"></span><span className="icon-bar"></span>
</button>
<a className="navbar-brand" href={this.data.brandLink}>AuthExample</a>
</div>
{this.props.hasUser ? <AuthenticatedNavigation /> : <PublicNavigation />}
</div>
</nav> );
}
});
AuthenticatedNavigation component :
AuthenticatedNavigation = React.createClass({
currentUserEmail() {
return Meteor.user().emails[0].address;
},
logout( event ) {
event.preventDefault();
return Meteor.logout( () =>
FlowRouter.go( '/login' ) );
},
render() {
return <div id="navbar-collapse" className="collapse navbar-collapse">
<ul className="nav navbar-nav">
<li className={FlowHelpers.currentRoute( 'hidden' )}>Hidden
</li>
</ul>
<ul className="nav navbar-nav navbar-right">
<li className="dropdown">
<a href="#" className="user-profile-toggle dropdown-toggle clearfix" data-toggle="dropdown">{this.currentUserEmail()} <span className="caret"></span>
</a>
<ul className="dropdown-menu" role="menu">
<li>Account Preferences</li>
<li className="logout" onClick={this.logout}>Logout</li>
</ul>
</li>
</ul>
</div>;
}
});
PublicNavigation Component:
PublicNavigation = React.createClass({
render() {
return (
<div id="navbar-collapse" className="collapse navbar-collapse">
<ul className="nav navbar-nav navbar-right">
<li className={FlowHelpers.currentRoute( 'login' )}>
<a href={FlowHelpers.pathFor( 'login' )}>Login</a>
</li>
</ul>
</div> );
}
}
);
Look at https://themeteorchef.com/snippets/authentication-with-react-and-flow-router/ for more details.

Silex: populate form with entered data after invalid submit

After the user submits a (uncomplete) form, I want the form to show the already entered data + an error message.
Using this code, the form is empty after submitting the form:
$request = $app['request'];
$form = $app['form.factory']->createBuilder('form')
->add('name', 'text', array( 'label' => 'Ihre Name:'))
->add('comment', 'text', array('constraints' => new Assert\Length(array('min' => 15))))
->getForm();
$twig_context = array('form' => $form->createView());
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
return 'valid!';
// Send form...
} else {
// display the form
return $app['twig']->render('contact.html.twig', $twig_context);
}
Twig-template:
{{ form_start(form) }}
{{ form_widget(form) }}
<div>
<input type="submit" value="Send" />
</div>
{{ form_end(form) }}
You should create the form view last, (could be right before you render your template). In your case, the view is created before the data from Request is applied.
This:
$twig_context = array('form' => $form->createView());
$form->handleRequest($request);
Should be:
$form->handleRequest($request);
And your render method should be:
return $app['twig']->render('contact.html.twig',
array(
'form' => $form->createView()
)
);

laravel search paginate Call to undefined method links()

Hi I have implemented a search facility in laravel it returns the search query but I also get this error in my laravel log as follows:
[2014-09-14 21:06:20] production.ERROR: exception
'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method
Illuminate\Database\Eloquent\Collection::links()' in
/media/sf_Sites/tempus/app/storage/views/424d7d6280a6a7c59b31268a6d17e44a:27
Stack trace:
#0 [internal function]: Illuminate\Exception\Handler->handleShutdown()
#1 {main} [] []
My code is as follows:
Projects/Index
#extends('layouts.master')
#section("content")
<div class="container">
<div>
{{ Form::open(['method' => 'GET', 'class' => 'nav-bar-form navbar-right']) }}
<div class="form-group">
{{ Form::input('search', 'q', null,['class' => 'form-control','placeholder' => 'Search']) }}
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
<p> {{ $project->project_name }}</p>
#endforeach
#else
<h5 class="errorslist">No match found</a></h5>
#endif
#endif
</div>
<div class="container">
<ul class="pagination">
<li>{{ $projects->links() }}</li>
</ul>
</div>
{{ Form::close() }}
#stop
Repository
public function searchProjects($query){
return \Project::where('project_name', 'LIKE', "%$query%" )
->orderby('project_name', 'asc')
->get();
}
public function getAll()
{
// get all logged in users projects and paginate 9 per page
return \Auth::user()->projects()->orderBy('project_name', 'asc')->paginate(9);
}
Controller:
public function index()
{
$query = Request::get('q');
$projects = $query
? $this->project->searchProjects($query)
: $this->project->getAll();
echo View::make('projects.index', compact('projects'));
}
Routes
Route::get('projects/index', array('before' => 'auth',
"as" => "projects/index",
"uses" => "ProjectController#index"
));
I'm not sure why I'm getting an error when I perform a search query on my links method, any ideas?
You need paginate on your searchProjects method as well:
public function searchProjects($query){
return \Project::where('project_name', 'LIKE', "%$query%" )
->orderby('project_name', 'asc')
->paginate(9);
}

Resources