I went to this tutorial. I got the example to work. But I don't get it because I can't customize it for my case.
I want to display a picture for each of my facebook friend and pass the adress of the profile picture from facebook to an image tag in front of the checkbox element.
Update
part of my action:
//the array is on part of my update.
$choice_test = array();
$choice_test[] = array('id' => 1, 'username' => 'test');
$choice_test[] = array('id' => 2, 'username' => 'test2');
->add('friend', 'choice', array(
'required' => true,
'expanded' => true,
'choice_list' => $choice_test, //this is my update
'choices' => $fb_friends_form, //$fb_friends_form[1]= 'First Lastane';
'multiple' => true,
'constraints' => array(new CheckChoicesFbFriends(array('fb_friends_form' => $fb_friends_form))),
'mapped' => true
))
return $this->render('FrontendChancesBundle::createrequest.html.php', array(
'form' => $form->createView()));
template:
<?php $view['form']->setTheme($form, array('FrontendDemoBundle:Form')) ;?>
<?php echo $view['form']->widget($form['friend'])?>
in FrontendDemoBundle/Ressources/views/Form/form_widget_pics.html.php:
<input
type="<?php echo isset($type) ? $view->escape($type) : 'checkbox' ?>"
<?php if (!empty($value)): ?>value="<?php echo $view->escape($value) ?>"<?php endif ?>
<?php echo $view['form']->block($form, 'checkbox_widget') ?>
/>
How can I pass even a variable, in my case the username (`$fb_username[0] = 'username' of facebook to from_widget_pics.html.php and how can I display it like this with the form bulider in my aciton:
<img src="www.facebook.com/+FirstLastname>
<input type="checkbox"
id="form_friend_0"
name="form[friend][]"
value="1"/>
<label for="form_friend_0" >First Lastname</label>
<img src="www.facebook.com/+nextfriend>
I had the very same exception message when trying to pass an array or collection of custom selected objects to a form using 'choice_list' option.
I solved it this way (simplified example):
Controller code:
use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;
class UsedCarsController extends Controller {
..... action code:
$usedCars = $carRepository->findAllUsed();
$choiceList = new SimpleChoiceList($usedCars);
$form = $this->createForm(new UsedCarsType($choiceList),null, array('label' => 'Used cars form'));
... now render view, etc.
UsedCarsType:
class UsedCarsType extends AbstractType
{
private $choicesList;
public function __construct($choicesList)
{
$this->choicesList = $choicesList;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('usedCars', 'choice',array('label'=>'Used cars',
'required'=>true,
'choice_list' => $this->choicesList,
'empty_value' => '-- used car --'))
;
}
Choice_list option must be an instance of SimpleChoiceList class, not an array.
A bit late but hope this helps.
BTW: I am using Symfony 2.3
Related
I have a select box created with formbuilder:
<select id="form_type" name="form[type]" class="form-control select2 select2-hidden-accessible" tabindex="-1" aria-hidden="true">
<option value="1">text</option>
<option value="2">hidden</option>
<option value="3">password</option>
<option value="4" selected="selected">icon</option>
<option value="5">select</option>
</select>
This is how it is created in my controller:
$formBuilder->add('type', EntityType::class, array(
'attr' => array('class' => 'form-control select2'), 'label' => 'Type',
'class' => FieldTypes::class,
'choice_label' => function ($fieldTypes) {
return $fieldTypes->getName();
}
));
$formBuilder->add('cancel', ButtonType::class, array('label' => 'cancel','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar')))
->add('save', SubmitType::class, array('label' => 'Save','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')));
$form = $formBuilder->getForm();
$form->handleRequest($request);
But when I want to save a selection I get the error message:
Argument 1 passed to App\Entity\Fields::setType() must be an instance
of App\Entity\FieldTypes or null, string given, called in
/Users/work/project/src/Controller/PagesController.php on line 242
In my entity:
public function setType(?FieldTypes $type): self
{
$this->type = $type;
return $this;
}
This is how it it stored:
$entity = $this->getDoctrine()->getRepository($EntityName)->find($data['form[id]']);
$em = $this->getDoctrine()->getManager();
foreach ($fields as $field) {
$em = $this->getDoctrine()->getManager();
$func = 'set'.$field['fieldName'];
$args = $data['form['.$field['fieldName'].']'];
$entity->$func($args);
}
$em->flush();
Use the method $form->handleRequest($request). It will populate your form using its configuration (it will instanciate a FieldType using the posted id).
Here, you add manually the "raw" value of your select, which is string containing the id of your FieldType.
edit : see the docs
According to your code, its little bit diffucult to understand but
if $field is as a string.
foreach ($fields as $field) {
$obj = $this->getDoctrine()->getRepository($fieldEntity)->find(field);
$entiy->setType($obj);
}
Try after form submit block
$entity->setType($form->get('type'));
$form->get('type') will return as a FieldTypes class.
also if you use $field instead of $field['fieldName'],
will object return.
for example,
$func = 'set'.$field;
I have a DateTimeWidget rendered by 2 fields:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('datetime', DateTimeType::class, [
'date_widget' => 'single_text',
'date_format' => 'dd/MM/yyyy',
'time_widget' => 'single_text',
]);
It generates as needed 2 field widget:
<input type="text" id="form_datetime_date" name="form[datetime][date]">
<input type="text" id="form_datetime_time" name="form[datetime][time]">
It works perfectly using the UI.
During my functional test, i want to submit the form having this input.
I tried
$form = $crawler->selectButton('my_submit')->form();
$form['form']['datetime'];
and
$form = $crawler->selectButton('my_submit')->form();
$form['form']['datetime']['date'] = new \DateTime('tomorrow');
$form['form']['datetime']['time'] = new \DateTime('tomorrow');
Writing this question I found the solution, I let it here if it can help someone
It has to be filled as text separately
$form->disableValidation();
$values = $form->getPhpValues();
$form['form']['datetime'] = [
'date'=> (new \DateTime('tomorrow'))->format('d/m/Y'),
'time'=> (new \DateTime('tomorrow'))->format('H:i'),
];
$crawler = $client->request($form->getMethod(), $form->getUri(), $values, $form->getPhpFiles());
Hy,
I'm really new to Zend-Framework 3 and I'm practicing OOP, I can't find a simple explanation/tutorial on making a Zend Form with a fieldset and legend. Basically I'm trying to create this in HTML:
<form name="my_name">
<fieldset>
<legend>My legend value</legend>
<input type="checkbox" name="name_1" value="value_1">Value 1</input>
<input type="checkbox" name="name_2" value="value_2">Value_2</input>
<input type="checkbox" name="name_3" value="value_3">Value_3</input>
</fieldset>
<input type="button" value="Get values" id="btn"/>
</form>
I checked the official documentation about Zend Forms and Collections and Fieldsets, but it's really confusing me. Any help would be greatly appreciated.
First, I am sorry as it is going to be a bit long one. But this would describe the form in action. So be patient please!
Assuming you are known to ZF3 default Application module. Some folders are created in the Application module for separation of each element. You need to create them as follows.
Let's get started by creating your fieldsets first. Zend\Form\Fieldset component represents a reusable set of elements and is dependent on Zend\From\Form component. This means you need to attach this to Zend\Form\Form.
module/Application/src/Form/Fieldset/YourFieldset.php
<?php
namespace Application\Form\Fieldset;
use Zend\Form\Element;
use Zend\Form\Fieldset;
class YourFieldset extends Fieldset
{
public function __construct($name = null)
{
parent::__construct('your-fieldset');
$this->add([
'name' => 'name_1',
'type' => Element\Checkbox::class,
'options' => [
'label' => 'Value 1',
'use_hidden_element' => true,
'checked_value' => 'yes',
'unchecked_value' => 'no',
],
'attributes' => [
'value' => 'no',
],
]);
// Creates others as your needs
}
}
Now we would create the form using Zend\From\Form attaching the fieldset created from Zend\From\Fieldset.
module/Application/src/Form/YourForm.php
<?php
namespace Application\Form;
use Application\Form\Fieldset\YourFieldset;
use Zend\Form\Form;
class YourForm extends Form
{
public function __construct($name = null)
{
parent::__construct('your-form');
$this->add([
// This name will be used to fetch each checkbox from
// the CheckboxFieldset::class in the view template.
'name' => 'fieldsets',
'type' => YourFieldset::class
]);
$this->add([
'name' => 'submit',
'attributes' => [
'type' => 'submit',
'value' => 'Get Values',
'class' => 'btn btn-primary'
],
]);
}
}
Our from is almost ready. We need to make it serviceable if we want it to be used in any action of a controller. So let's do that.
Update your module config file. If service_manager key does not exist then add the following snippet of code, otherwise, update only factories and aliases key as the following.
Fix namespaces in module config file.
module/Application/config/module.config.php
'service_manager' => [
'factories' => [
// Form service
Form\YourForm::class => Zend\ServiceManager\Factory\InvokableFactory::class,
// Other services
],
'aliases' => [
// Make an alias for the form service
'YourForm' => Form\YourForm::class,
],
],
Now the form is ready to be used. This needs to be injected into our controller. As I am working on Application module, I would inject the form into the IndexController::class's constructor. Then we would be using that form inside IndexController::fieldsetAction() method.
module/Application/src/Controller/IndexController.php
<?php
namespace Application\Controller;
use Zend\Form\FormInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
protected $YourForm;
public function __construct(FormInterface $YourForm)
{
$this->YourForm = $YourForm;
}
public function fieldsetAction()
{
$request = $this->getRequest();
$viewModel = new ViewModel(['form' => $this->YourForm]);
if (! $request->isPost()) {
return $viewModel;
}
$this->YourForm->setData($request->getPost());
if (! $this->YourForm->isValid()) {
return $viewModel;
}
$data = $this->YourForm->getData()['fieldsets'];
echo '<pre>';
print_r($data);
echo '</pre>';
return $viewModel;
}
}
As this controller is taking argument in its constructor, we need to create a factory for this controller (a factory creates other objects).
module/Application/src/Factory/Controller/IndexControllerFactory.php
<?php
namespace Application\Factory\Controller;
use Application\Controller\IndexController;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
class IndexControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
// We get form service via service manager here
// and then inject controller's constructor
$YourForm = $container->get('YourForm');
return new IndexController($YourForm);
}
}
Once again, we need to update the module config file. We would add this time the factory under controllers key as follows
'controllers' => [
'factories' => [
Controller\IndexController::class => Factory\Controller\IndexControllerFactory::class,
],
],
At the end, echo the form in the view template as follows:
module/Application/view/application/index/fieldset.phtml
<h1>Checkbox Form</h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url());
// Here is the catch, remember this name from the CheckboxForm::class
$fieldset = $form->get('fieldsets');
$name_1 = $fieldset->get('name_1');
$name_2 = $fieldset->get('name_2');
$name_3 = $fieldset->get('name_3');
$submit = $form->get('submit');
$submit->setAttribute('class', 'btn btn-primary');
$form->prepare();
echo $this->form()->openTag($form);
?>
<fieldset>
<legend>My legend value</legend>
<?= $this->formElement($name_1) ?>
<?= $this->formLabel($name_1) ?>
<?= $this->formElement($name_2) ?>
<?= $this->formLabel($name_2) ?>
<?= $this->formElement($name_3) ?>
<?= $this->formLabel($name_3) ?>
<?= $this->formSubmit($submit) ?>
</fieldset>
<?php
echo $this->form()->closeTag();
Hope this would help you!
Actually the example you are looking for is in "collections" part of zend form. Its not the exact one but kinda like.
Here you are a little example. I ignored namespaces and hope so there's no typo :)
class myFieldset extends Fieldset {
public function init(){
$this
->add([
'name' => 'name_1,
'type' => 'text',
])
->add([
'name' => 'name_2,
'type' => 'text',
])
->add([
'name' => 'name_3,
'type' => 'text',
]);
}
}
class MyForm extends Form {
public function init(){
$this->add([
'type' => myFieldset,
'name' => 'fieldset'
])->add([
'type' => 'button',
'name' => 'action'
]);
}
}
And in view file;
<?=$this-form($form);?>
I have a the register button which I have created in cgridview I need to know whether can we have action in controller buuton and no view for that particular action for that button in yii
view user
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'product-grid',
'dataProvider'=>$model->countregister($_GET['id']),
'enablePagination' => true,
'filter'=>$model,
'columns'=>array(
'name',
'email',
array(
'class'=>'CButtonColumn',
'template'=>'{Register}{update}{view}',
'buttons'=>array(
'Register'=>array(
'label'=>'Register',
.'url'=>Yii::app()->createUrl('register/create',array( 'email'=>$data->email) )
)
),
),
),
)); ?>
controller user
public function actionCreate($email)
{
$model=$this->loadModel($email);
if($_SESSION['userid'])
{
$this->redirect('product/create',array( //line 1
'model'=>$model,'id'=>$model->productid,
));
}
//$this->redirect(array('display','id'=>$model->productid));
$this->redirect(array('user/login'));
}
i don get error but then the below line not the url iam looking
/localhost/test/index.php/register/create/product/create
it should be
/localhost/test/index.php/product/create/id/1
i think there's something wrong in line 1
Please let me know how do i resolve this
change this
$this->redirect('product/create',array( //line 1
'model'=>$model,'id'=>$model->productid,
to
$this->redirect(Yii::app()->createUrl('product/create',array( //line 1
'id'=>$model->productid))
You can parametrise your individual CButtonColumn instances:
array(
'class' => 'CButtonColumn',
'template' => '{Register}{view}{update}',
'buttons' => array(
'Register' => array(
'label' => 'Register',
'url'=>Yii::app()->createUrl('register/create', array('email' => $data->email)),
'visible'=>'$data->entries == 0',
),
'view' => array(
'visible'=>'$data->entries > 0',
)
)
),
But to answer you question after you updated your response (I was already typing it out)
You can use the raw type:
'type'=>'raw',
and the url becomes something like :
'url'=>'Yii::app()->createUrl("register/create",array( "email"=>$data->email) )'
thx to #let-me-see
source: http://www.yiiframework.com/wiki/106/using-cbuttoncolumn-to-customize-buttons-in-cgridview/#hh2
this works
$this->redirect(array('product/create','id'=>$model->productid));
I embed one form to another. I need to add HTML attributes to the fields embedded form.
Trying to do so:
$this->widgetschema['email'] = new sfWidgetFormInputText(array(), array('class' => 'email'));
but it does not work.
Did you try it this way?
creating a class
class YourForm extends sfForm {
$array= array('array');
$this->setWidgets(array(
'field1' => new sfWidgetFormSelect(array('choices' => $array), array('placeholder' => 'field1', 'required' => 'true', 'data-empty' => 'U did not enter field1!')),
'email_address' => new sfWidgetFormInputText(array('type' => 'email'), array())
));
}
You can even change the type in the first array. Then include your form in the actions by calling it like
$this->form = new YourForm();
Then echo your form in the template:
<?php echo $form; ?>
I hope this helps. I use it like this as well, to add extra attributes to use in javascript.