I am trying to make a sell item page. The form and page render
I'm not entirely sure what I am doing wrong, but when I hit the submit I get an error 500. There might be a syntax error that I am not catching
I have the parameter set as image_directory: '%kernel.root_dir%/../web/images'
class SellPage extends Controller
{
/**
* #Route("/SellItem", name="Sell_Item")
*/
public function goToSellPage(Request $request)
{
$item = new Item();
$sellForm = $this->createFormBuilder($item)
->setMethod("POST")
->add('name', TextType::class, array('label' => 'Item Name: ', 'attr' => array('class' => 'form-control form-group')))
->add('price', TextType::class, array('label' => 'Price: ', 'attr' => array('class' => 'form-control form-group')))
->add('image', FileType::class, array('label' => 'Image Upload Click Here', 'attr' => array('class' => 'btn btn-lg form-group')))
->add('description', TextareaType::class, array('label' => 'Description', 'attr' => array('class' => 'form-control form-group')))
->add('category', EntityType::class, array('class' => 'AppBundle\Entity\Category', 'choice_label' => 'name', 'label' => 'Category', 'attr' => array('class' => 'form-control form-group')))
->add('seller', EntityType::class, array('class' => 'AppBundle\Entity\User', 'choice_label' => 'userName', 'label' => 'Seller', 'attr' => array('class' => 'form-control form-group')))
->add('save', SubmitType::class, array('label' => 'Submit', 'attr' => array( 'class' => 'btn btn-lg btn-success form-group')))
->getForm();
$sellForm->handleRequest($request);
if ($sellForm->isValid())
{
$formData = $request->request->get('sellForm');
$item->setName($formData['name']);
$item->setPrice($formData['price']);
$item->setDescription($formData['description']);
$repository = $this->getDoctrine()->getManager()->getRepository('AppBundle:User');
$item->setSeller($repository->getUserByName($item->getSeller()));
$item->setBuyer($repository->find(2));
$fileName = 'http://sfsuse.com/~sp17g01/sp17g01/web/images/'.md5(uniqid()).$sellForm['image']->getData()->guessExtension();
$sellForm['image']->getData()->move(
$this->getParameter('image_directory'),
$fileName);
$item->setImage($fileName);
$catRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Category');
$item->setCategory($catRepository->find(1));
$em = $this->getDoctrine()->getManager();
$em->persist($item);
$em->flush();
}
return $this->render('default/SellItem.html.twig',['sellForm' => $sellForm->createView(),]);
}
}
In you parameters.yml file use:
image_directory: images
And I also think you need to change $filename like so:
$fileName = 'images/'.md5(uniqid()).$sellForm['image']->getData()->guessExtension();
If you are getting errors, it's best to append app_dev.php to your symfony app URL (debug URL). So for example on localhost use:
http://localhost/app_dev.php
And then point to route by appending the route, example:
http://localhost/app_dev.php/myRoute
Then you will get more debug info. I suggestion using the deubg URL for development use.
Try to use this construction:
if ($form->isSubmitted()) {
if ($form->isValid()) {
$img = $user->getImg();
if ($img !== null) {
$img = $user->getImg();
$fileName = md5(uniqid()).'.'.$img->getExtension();
$img->move(
$this->getParameter('user_images'),
$fileName
);
$user->setImg($fileName);
}
}
}
Related
I am using SgDatatablesBundle 1.0
The datatable is rendred with a line on the top contain inputfileds!
I dont know how to remove it ,Please any help
I have follwed this link to use the bundle :
https://github.com/stwe/DatatablesBundle/blob/master/Resources/doc/installation.md#your-first-datatable
my class postDatatable:
namespace AppBundle\Datatables;
/**
* Class PostDatatable
*
* #package AppBundle\Datatables
*/
class PostDatatable extends AbstractDatatable
{
/**
* {#inheritdoc}
*/
public function buildDatatable(array $options = array())
{
$this->language->set(array(
'cdn_language_by_locale' => true
//'language' => 'de'
));
$this->ajax->set(array( 'url' => $this->router->generate('app_homepage'),
'type' => 'GET'
));
$this->options->set(array(
'individual_filtering' => true,
'individual_filtering_position' => 'head',
'order_cells_top' => true,
));
$this->features->set(array(
));
$this->columnBuilder
->add('name', Column::class, array(
'title' => 'Name',
))
->add('nbPges', Column::class, array(
'title' => 'NbPges',
))
->add('subject', Column::class, array(
'title' => 'Subject',
))
->add(null, ActionColumn::class, array(
'title' => $this->translator->trans('sg.datatables.actions.title'),
'actions' => array(
array(
'route' => 'app_homepage',
'route_parameters' => array(
'id' => 'id'
),
'label' => $this->translator->trans('sg.datatables.actions.show'),
'icon' => 'glyphicon glyphicon-eye-open',
'attributes' => array(
'rel' => 'tooltip',
'title' => $this->translator->trans('sg.datatables.actions.show'),
'class' => 'btn btn-primary btn-xs',
'role' => 'button'
),
),
array(
'route' => 'app_homepage',
'route_parameters' => array(
'id' => 'id'
),
'label' => $this->translator->trans('sg.datatables.actions.edit'),
'icon' => 'glyphicon glyphicon-edit',
'attributes' => array(
'rel' => 'tooltip',
'title' => $this->translator->trans('sg.datatables.actions.edit'),
'class' => 'btn btn-primary btn-xs',
'role' => 'button'
),
)
)
))
;
}
/**
* {#inheritdoc}
*/
public function getEntity()
{
return 'AppBundle\Entity\Post';
}
/**
* {#inheritdoc}
*/
public function getName()
{
return 'post_datatable';
}
}
Take a look at the available options.
You need to set individual_filtering to false to remove the search input fields.
I have two entities. First is Clinic an second is ClinicOpeningHours.
ClinicOpeningHours is mapped by Clinic id, but not in revers. I'm trying to find solution to get whole (7) records (mon - sun) and join it in ClinicFormType to have all this in one form.
$clinic = $em->getRepository('MyEntity:Clinic')->findOneBy(array(etc));
$form = $this->createForm(new ClinicFormType(), $clinic);
My form type:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('name', 'text', array('label' => 'Name'));
$builder->add('services', 'entity', array(
'class' => 'MyEntity:Service',
'property' => 'name',
'label' => 'Services',
'required' => false,
'multiple' => true,
'attr' => array(
'data-placeholder' => "Choose one...",
'multiple' => 'multiple',
'class' => "chzn-select"
)
))
->add('WEEK DAYS', 'entity', array(
'label' => 'Property Language',
'class' => 'MyEntity:ClinicOpeningHours',
'query_builder' => SEVER RECORDS FROM DB MAPPED BY ID
},
));
}
I asked a question here How to use Repository custom functions in a FormType but nobody anwsered, so i did a little digging and advanced a little but i still get this error:
Notice: Object of class Proxies\__CG__\Kpr\CentarZdravljaBundle\Entity\Category
could not be converted to int in /home/kprhr/public_html/CZ_Symfony/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php line 457
Now this is how my CategoryType looks like:
<?php
namespace Kpr\CentarZdravljaBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;
class CategoryType extends AbstractType
{
private $doctrine;
public function __construct(RegistryInterface $doctrine)
{
$this->doctrine = $doctrine;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Kpr\CentarZdravljaBundle\Entity\Category',
'catID' => null,
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$someId = $builder->getData()->getId();
$param = ($someId) ? $someId : 0;
$catID = $options['catID'];
$builder->add('name', 'text', array('attr' => array('class' => 'span6')));
$builder->add('file', 'file', array('image_path' => 'webPath', 'required' => false));
$builder->add('parent', 'choice', array(
'choices' => $this->getAllChildren($catID),
'required' => false,
'attr' => array('data-placeholder' => '--Izaberite Opciju--'),
));
$builder->add('tags', 'tag_selector', array(
'required' => false,
));
$builder->add('status', 'choice', array(
'choices' => array('1' => 'Aktivna', '0' => 'Neaktivna'),
'required' => true,
));
$builder->add('queue', 'text', array('attr' => array('class' => 'span3')));
}
private function getAllChildren($catID)
{
$choices = array();
$children = $this->doctrine->getRepository('KprCentarZdravljaBundle:Category')->findByParenting($catID);
foreach ($children as $child) {
$choices[$child->getId()] = $child->getName();
}
return $choices;
}
public function getName()
{
return 'category';
}
}
I am accessing the CategoryRepository function findByParenting($parent) from the CategoryType and I am getting the array populated with accurate data back from the function getAllChildren($catID) but the error is there, i think that Symfony framework is expecting an entity field instead of choice field, but dont know how to fix it.
I also changet the formCreate call in the controller giving $this->getDoctrine() as an argument to CategoryType():
$form = $this->createForm(new CategoryType($this->getDoctrine()), $cat, array('catID' => $id));
Ok i managed to resolve the dilemma. The answer was easy all I had to do is change
$builder->add('parent', 'choice', array(
'choices' => $this->getAllChildren($catID),
'required' => false,
'attr' => array('data-placeholder' => '--Izaberite Opciju--'),
));
to this:
$builder->add('parent', 'entity', array(
'class' => 'KprCentarZdravljaBundle:Category',
'choices' => $this->getAllChildren($catID),
'property' => 'name',
'required' => false,
'attr' => array('data-placeholder' => '--Izaberite Opciju--'),
));
And change the getAllChildren(..) function so that it returns objects
private function getAllChildren($catID)
{
$choices = array();
$children = $this->doctrine->getRepository('KprCentarZdravljaBundle:Category')->findByParenting($catID);
foreach ($children as $child) {
$choices[$child->getId()] = $child->getName();
}
return $choices;
}
I changed it to:
private function getAllChildren($catID)
{
$children = $this->doctrine->getRepository('KprCentarZdravljaBundle:Category')->findByParenting($catID)
return $children;
}
Lots of thanks to user redbirdo for pointing out the choices option on an entity field.
It seems like you are doing something too much complicated.
You are on the right way when you write Symfony framework is expecting an entity field instead of choice field.
To do this, replace:
$builder->add('parent', 'choice', array(
'choices' => $this->getAllChildren($catID),
'required' => false,
'attr' => array('data-placeholder' => '--Izaberite Opciju--'),
));
by:
$builder->add('users', 'entity', array(
'class' => 'KprCentarZdravljaBundle:Category',
'property' => 'name',
'query_builder' => function(EntityRepository $er) use($catID) {
return $er->findByParenting($catID);
},
'required' => false,
'empty_value' => '--Izaberite Opciju--'
));
(and you don't need getAllChildren($catID) anymore unless used somewhere else)
http://symfony.com/doc/current/reference/forms/types/entity.html
I created form EditFormType with code:
// ...
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
$builder->addEventSubscriber(new UnsetReadOnlyForEmailField());
}
// ...
and UnsetReadOnlyForEmailField:
// ...
public static function getSubscribedEvents()
{
return array(
FormEvents::PRE_SET_DATA => 'preSetData'
);
}
public function preSetData(FormEvent $event)
{
$form = $event->getForm();
$data = $event->getData();
if ($data === null) {
return;
}
if ($data->getId() === null) {
$form->add(
'plainPassword',
'repeated',
array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle', 'required' => true),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
)
);
}
}
// ...
Unfortunately required for repeated field doesn't work, field is't required. Any suggestions? If I do it wrong, then please write to set the fields in the form are required or not, depending on the form to edit or add. On add form required, on edit form not required.
I think you can do it in such way:
$form->add(
'plainPassword',
'repeated',
array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array(
'label' => 'form.password',
'required' => true
),
'second_options' => array(
'label' => 'form.password_confirmation',
'required' => true
),
'invalid_message' => 'fos_user.password.mismatch',
)
);
I have selected an entity/record from the database and pass it to my form. The form loads correctly, but when I hit save it adds a new record instead of updating the existing one.
PlanController.php
public function editPlanAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$plan = $em->getRepository('etrakOnlineOrderProcessingBundle:Plan')->find($id);
if (!$plan && !$request->isMethod('POST')) {
throw $this->createNotFoundException(
'No plan found for id ' . $id
);
}
$form = $this->createForm(new PlanType(), $plan);
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$editPlan = $form->getData();
$em->flush();
}
}
return $this->render('etrakCustomerServiceBundle:Plan:edit.html.twig', array('form' => $form->createView()));
}
routing.yml
etrak_customer_service_plan_edit:
pattern: /plan/edit/{id}
defaults: { _controller: etrakCustomerServiceBundle:Plan:editPlan }
PlanType.php
namespace etrak\CustomerServiceBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PlanType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'etrak\OnlineOrderProcessingBundle\Entity\Plan',
'cascade_validation' => true,
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$termsConditionsArray = array("NONE" => "No Contract", "1 Year Contract" => "1 Year Contract", "2 Year Contract" => "2 Year Contract");
$billingFrequencyArray = array("1" => "Monthly", "6" => "6 Months", "12" => "Yearly");
// Create the form
$builder->add('name', 'text', array('label' => 'Plan Name: ', 'required' => false));
$builder->add('description', 'text', array('label' => 'Plan Description: ', 'required' => false));
$builder->add('termsConditions', 'choice', array('choices' => $termsConditionsArray, 'label' => 'Terms & Conditions', 'required' => false));
$builder->add('amount', 'text', array('label' => 'Plan Price: ', 'required' => false));
$builder->add('affinity', 'choice', array('choices' => array('0' => 'Yes', '1' => 'No'), 'label' => 'Affinity? ', 'expanded' => true, 'required' => false));
$builder->add('deactivationFee', 'text', array('label' => "Deactivation Fee: ", 'required' => false));
$builder->add('recurringInMonths', 'choice', array('choices' => $billingFrequencyArray, 'label' => 'Billing Frequency: ', 'required' => false));
$builder->add('pricingTier', 'entity', array(
'class' => 'etrakOnlineOrderProcessingBundle:pricingTier',
'property' => 'name',
'label' => "Select Pricing Tier: "
));
$builder->add('activeStartDate', 'datetime', array('label' => "Effective Start Date: ", 'required' => false));
$builder->add('activeEndDate', 'datetime', array('label' => "Effective End Date: ", 'required' => false));
}
public function getName()
{
return 'plan';
}
}
Any help would be greatly appreciated!
The problem is that you not posting the id of the plan object. Hence a new one is being created when you do the getData. Add id as a hidden field or add it to your post url in the template. Actually, I don't think the hidden field will work. Probably need to just update the post url.
if ($form->isValid()) {
$editPlan = $form->getData();
$em->persist($editPlan);
$em->flush();
}
Maybe you forget to persist entities.