mercredi 1 avril 2015

Validated optional nested form in Symfony2

Is there a way in Symfony2 to add an optional nested form while using cascade validation? In other words, say I have a user form with a nested address form (->add('adresse', new AddressType(), array('required' => false))). This address is not required BUT must be validated in case the user specify it ('cascade_validation' => true).


UPDATE


Relevant entities and forms :


User entity (Getters & Setters are classical, Symfony generated):



class User
{
[...]

/**
* @var \Address
*
* @ORM\OneToOne(targetEntity="Address", cascade="persist")
* @ORM\JoinColumn(
* name="address_id", referencedColumnName="id"
* )
*/
private $address;

[...]
}


The address entity is classical, no bidirectionnal relation to user.


User form



class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
[...]
->add('address', new AddressType(), array('required' => false))
[...]
;
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Xentia\FuneoBundle\Entity\User',
'cascade_validation' => true
));
}

public function getName()
{
return 'user';
}
}


The address nested form is classical


As you can see, the is a quite classical and straightforward code. The only particular case is that address is optional. Leading to an validation error only in the case that the address was previously set (and, thus, exist in the DB and as a not null relation with the user) and the user want to unset it (all address fields are left empty). It seems that if the related address has not an actual instance it can still be optional. But, if an instance of the address exist and is linked with the user, it can not be optional anymore.


So, what should it do: When the user update his profile, if there was a previously set address and he try to unset it, user->address should be set to NULL and the address should be deleted. What does actually happens: The form throw a validation error saying that the address fields are not set. But, as the address is optional, such validation error should not occur. And, in fact, it does not occur if the address was not set before the user update his profile, it only occurs if there was an address previously set.


Symfony2 multiple Entities of same class in one Form

I want to render a form which has multiple Entities of same Class. I will display 2 fields, Price(type=text) and Enabled(type=checkbox).


I don't know how many I will have of those entities, so form will have to get them dynamically.


I have tried to do the following



public function buildForm(FormBuilderInterface $builder, array $options)
{

$builder
->add('price', 'text', array(
'label' => 'Price',
'required' => true
))
->add('enabled','checkbox',array(
'label' => 'Use this currency',

))
;
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Osiris\Entity\Pricing',
'csrf_protection' => false
));
}

public function getName()
{
return 'pricingtype';
}


And in my Controller I have created my form like this:



$pricingForm = $this->createFormBuilder($prices)
->add('items','collection',array(
'required' => false,
'prototype' => true,
'type' => new PricingType(),
))
->getForm()
;


In my twig I do:



{% for price in form_pricing %}
<h2>Price</h2>
<div class="row">{{ form_widget(price) }}</div>
{% endfor %}


However it comes only with h2 Prices and empty div with class=row. I feel like I am half way there, but I've no idea how to move on. If someone knows how to get fields on submit as well, I will really appreciate it.


How to grab data from static table (HTML) and put it in a form field when pressing button

I have a simple HTML website and a static (no database) table with informations.


Can you help me explain how could I grab a whole row data by checking a check box and pressing an "order selected above" button and then paste it in a form on the end of the page?


How it should work for all table rows - this is just an example


All I need is the data caopied from the table and pasted in a contact body form at the end of the page.


Thanks, Robert!


Form submit via JQuery: Ajax fails if form parameters have spaces?

I have a form which submits asynchronously via .trigger("submit") just fine if one of the form's fields have no spaces in it, and submits NOT asynchronously (that is, the page location changes to the form's action attribute) if the same field has spaces in it.


Is this a known bug? Does a workaround exists?


Submit a PHP form with the link in Python

At the moment I have a PHP form submit link. I can paste this in the browser and it will run. But I need an automation. And I want to "send" this in Python so that the form will submitted.


Thanks for your answers:)


Sitecore Web form for marketer not working

I am using sitecore 7.2 & I have installed "Web Forms for Marketers 2.4 rev. 141008" sucessfully, now I created an new form have some fields (single-line,telephone,email) when i submit this form it through an error "We experienced a technical difficulty while processing your request. Your data may not have been correctly saved."


Form to comment in DataObject, SilverStripe 3.1.12

I have this structure...:


Products>mysite>code>Products>Product.php


I have my product like DataObject and ContentController to create form and handle on backend...

class Product extends DataObject
{
//...
}

class Product_Controller extends ContentController
{
private static $allowed_actions = array(
'CommentForm'
);

public function CommentForm()
{
$form = Form::create(
this,
__FUNCTION__,
FieldList::create(
TextField::create('Name',''),
EmailField::create('Email',''),
TextareaField::create('Comment','')
),
FieldList::create(
FormAction::create('handleComment', 'Post Comment')
->setUseButtonTag(true)
->addExtraClass('btn btn-default-color btn-lg')
),
RequiredFields::create('Name','Email', 'Comment')
)->addExtraClass('form-style');

foreach($form->Fields() as $field){
$field->addExtraClass('form-control')
->setAttribute('placeholder', $field->getName(), '*');
}

$data = Session::get("FormData.{$form->getName()}.data");

return $data ? $form->loadDataFrom($data) : $form;
}

public function handleComment($data, $form){
Session::set("FormData.{$form->getName()}.data", $data);
$existing = $this->CommentForm()->Comments()->filter(array(
'Comment' => $data['Comment']
));
if($existing->exists() && strlen('Comment') > 20){
$form->sessionMessage('That comment already exists!', 'bad');

return $this->redirectBack();
}

$comment = ProductComment::create();
$comment->ProductID = $this->ID;
$form->saveInto($comment);
$comment->write();

Session::clear("FormData.{$form->fetName()}.data");
$form->sessionMessage('Thanks for your comment', 'good');

return $this->redirectBack();

}

}


Products>mysite>code>Products>ProductsPage.php


Page with many Products...

class ProductsPage extends Page
{

private static $has_many = array(
'Products' => 'Product',
'Categories' => 'Category'
);
//...
}
class ProductsPage_Controller extends Page_Controller
{
private static $allowed_actions = array (
'show'
);

public function show(SS_HTTPRequest $request)
{
$product = Product::get()->byID($request->param('ID'));

if (!$product) {
return $this->httpError(404, 'That region could not be found');
}

return array(
'Product' => $product,
'Name' => $product->Name
);
}
}


Products>mysite>code>extensions>ProductExtension>ProductComments.php


Is a DataExtension with many comments...

class ProductComments extends DataExtension{

private static $has_many = array(
'Comments' => 'ProductComment'
);
}


Products>mysite>code>extensions>ProductExtension>ProductComment.php


A simple DataObject to comment...

class ProductComment extends DataObject
{
private static $db = array(
'Name' => 'Varchar',
'Email' => 'Varchar',
'Comment' => 'HTMLText'
);

private static $summary_fields = array(
'Created' => 'Created',
'Name' => 'Name',
'Email' => 'Email',
'Comment' => 'Text'
);
private static $has_one = array(
'Product' => 'Product'
);
public function getCMSFields(){
$fields = FieldList::create(
TextField::create('Name'),
TextField::create('Email'),
HtmlEditorField::create('Comment')
);
return $fields;
}
}


My file config.yml to add extension comments...


Products>mysite>_config>config.yml



Product:
extensions:
- ProductComments


SilverStripe files (.ss)...


Products>themes>my_theme>templates>Layout>ProductsPage.ss


Little view to products...

<% loop $Products %>
<div class="item col-md-2"><!-- Set width to 4 columns for grid view mode only -->
<div class="image">
<a href="$Link">
$Main_image.CroppedImage(175,150)
</a>
</div>
<div class="item">
<h3>
<a href="$Link">$Name</a>
</h3>
$Short_description
</div>
</div>
<% end_loop %>


Products>themes>my_theme>templates>Layout>ProductsPage_show.ss


View to see info and comment product.

<% with $Product %>
<%--...--%>
<h1>Comments</h1>
<% loop $Comments %>
<div class="comment">
<h3>$Name <small>$Created.Format('j F,Y')</small></h3>
<p>$Comment</p>
</div>
<% end_loop %>

<div class="comments-form">
<h3>Leave a Reply</h3>
<p>Your email address wlill no be published. Required fields are marked*</p>

$CommentForm
</div>
<% end_with %>


I can´t extend ContentController from DataObject, it´s wrong... What would be the best way to posting a product that is DataObject? I´ve seen this post Submit Form in Dataobject - Silverstripe 3.1 I can't it working.