CUploadedFile::getInstance Always Returns Null on Uploaded File - forms

I have built a form in YII and I need to process an uploaded file. I followed this guide, but I've stumbled upon an issue. CUploadedFile::getInstance always returns null.
Here's what I use. My model:
class AdditionalFieldFile extends CFormModel {
public $uploadedFile;
/**
* #return array validation rules for model attributes.
*/
public function rules() {
return array(
//note you wont need a safe rule here
array('uploadedFile', 'file', 'allowEmpty' => true, 'types' => 'zip,doc,xls,ppt,jpg,gif,png,txt,docx,pptx,xlsx,pdf,csv,bmp'),
);
}
}
And handling the uploaded file in the controller on form submit:
$model = new AdditionalFieldFile();
$model->uploadedFile = CUploadedFile::getInstance($model, 'field_'.$type_field.'['.$id_common.']');
And after that $model->uploadedFile is null for some reason.
Note that $type_field and $id_common come dynamically.
Also, the form has 'enctype'=>'multipart/form-data' so this is not the cause.

Ok, a self-answer follows.
It turns out that I had to use the active file field in the view, using an instance of the class that extends CFormModel as a model.
Solution:
CHtml::activeFileField(new AdditionalFieldFile(), 'field_'.$type_field.'['.$id_common.']');

Related

Laravel one to many relationship save method empty attributes

I am trying to save a relationship with the Laravel save method:
public function storeContact(Request $request)
{
$user = User::firstOrNew(['email' => $request->input('email')]);
$user->save();
$message = new App\Message([
'message' => $request->input('remarks')
]);
$user->message()->save($message);
}
var_dump($request->all) confirms both fields are available in the request.
All relations work. hasOne, belongsTo are configured in the models. The relation is saved like expected (but message field is empty)
When I var_dump($message), there are no attributes in the collection.
I already tried fillable and guarded on the models without any effect. These should not be necessary for the save method though because this uses a full Eloquent model instance.
What am I missing here??
I think I found the culprit.
When I use a __construct on a model it fails. When I instantiate a model with a __construct no variables are passes as attributes. Even if the __construct is empty.
Test with __construct method
class Message extends Model
{
protected $connection = 'system';
public function __construct()
{
}
// ...
}
$message = new App\Message(['remarks' => 'Test remarks']);
var_dump(message) // does NOT contain attributes!
Test2 without __construct method
class Message extends Model
{
protected $connection = 'system';
// ...
}
$message = new App\Message(['remarks' => 'Test remarks']);
var_dump(message) // does contain attributes!
This looks like a bug in Laravel to me.

Extbase property mapping for deleted record

I would like to build a preview page for a create form. I set "deleted" property of the record to "1" when in previewAction because in the BE the list module is used to approve the inserted records - so if the record was never finally saved its deleted anyway.
Problem: I can create the record (deleted=1) - I can jump back to the form (no history back for I have to keep the created object). But if I submit again the property mapping tells me
Object of type MyModel with identity "3" not found.
Of course that's because its deleted. The settings in the Repository to ignore deleted are not taking action here.
Yes I could bypass the Extbase magic by filling up everything manually, but this is not what I want.
Here is the action to get an idea what I'm trying
/**
* action preview
*
* #param MyModel
* #return void
*/
public function previewAction(MyModel $newModel)
{
//check if model was already saved
$uid = $this->request->hasArgument('uid') ? this->request->getArgument('uid') : 0;
if($uid){
$newModel = $this->myRepository->findDeletedByUid($uid);
$this->myRepository->update($newModel);
}
else{
$newModel->setDeleted(true);
$this->myRepository->add($newModel);
}
$this->view->assign('ad', $newModel);
$this->persistenceManager->persistAll();
$uid = $this->persistenceManager->getIdentifierByObject($newModel);
$this->view->assign('uid', $uid);
}
Any ideas?
The Extbase default query settings suppress deleted objects.
Since you've already stated the custom query findDeletedByUid() in your repository, you just need to set it to include deleted records. It is important, however, that if you want to call your controller action using the object, you'll have to retrieve it before calling the action. Use an initialization action for that. The initializaton will be called automatically before the action.
If you want to set wether the object is deleted, you'll also going to need to define a property, getter and setter in your Domain Model and a proper definition in your tca to enable the data mapper to access the column.
In the repository:
public function findDeletedByUid($uid) {
$query = $this->createQuery();
$query->getQuerySettings()->setIncludeDeleted(true);
$query->matching(
$query->equals('uid',$uid)
);
return $query->execute();
}
In your Controller class:
/**
* initialize action previewAction
* Overrides the default initializeAction with one that can retrieve deleted objects
*/
public function initializePreviewAction(){
if( $this->request->hasArgument('mymodel') ){
$uid = $this->request->getArgument('mymodel');
if( $mymodel = $this->mymodelRepository->findDeletedByUid($uid) ){
$this->request->setArgument($mymodel);
} else {
// handle non retrievable object here
}
} else {
// handle missing argument here
}
}
In your Domain Model:
...
/**
* #var bool
*/
protected $deleted;
/**
* #return bool
*/
public function getDeleted() {
return $this->deleted;
}
/**
* #param bool $deleted
*/
public function setDeleted($deleted) {
$this->deleted = $deleted;
}
In your tca.php
...
'deleted' => array(
'exclude' => 1,
'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.deleted',
'config' => array(
'type' => 'check',
),
),
Instead of doing any magic with deleted, you should use the hidden field to allow editors to preview documents.
You can tell your query to include hidden records inside the repository.
Your findDeletedByUid($uid) function caught my eye. If it's not a custom function, should it use something like findByDeleted(TRUE) or findByDeleted(1) in combination with ->getFirst() or ->findByUid()? You can find discussions in the Extbase manual reference and the Repository __call() function API sections.
Thanks for all hints.
I think depending to the answers its not possible without bypass extbase property-mapping magic. So I think in general its not a good idea to do it like that.
So I put now my own flag "stored" to the model.
In BE List-Module the not "stored" objects are still visible, but using an own BE Module or deleting the not "stored" object by a cron-job should do the job.
If anyone has a bedder idea feel free to share it :-)

Check if a specific validation_group is valid in Symfony Form?

I'm building a complex symfony form which is a bit long and contains other embedded forms. Thus the form is displayed in the UI in separate tabs to make it more readable and convenient for the user.
Because the form is long and separated in the UI there is a chance you've missed something while populating it or you just inserted something incorrect. That's when the validation would kick in and stop the form from being saved. The validation itself is configured and works flawlessly.
My problem here is I have a gigantic form, separated in tabs, which has an error somewhere and I need to browse each one of the tabs to see exactly what's wrong. I was thinking to make that specific tab, containing fields with errors, in another color so it could stand out and save you the time of wondering what's wrong and where it is located.
From what I could see, I have two options:
Check all fields per tab, manually, using something like:
{% if not form.children.FIELD_NAME.vars.valid %}
which would take forever to complete and I would do only if it's the only possible way.
Try using validation_groups => array('Default', 'my_tab_name') and logically group the fields for each tab.
I'm really hoping to use the second method, but I can't seem to figure out how to check if the validation group i.e. my_tab_1 contains any errors. I'm aware I can do something like this:
$validator = $this->get('validator');
$my_tab_1 = $validator->validate($entity, null, array('my_tab_1'));
$my_tab_2 = $validator->validate($entity, null, array('my_tab_2'));
$my_tab_3 = $validator->validate($entity, null, array('my_tab_3'));
// so on
But the form is already being validated with $form->validate() and using this approach would trigger N more unnecessary validations.
So the question here is how to check if a specific validation group is valid from a twig template? If that's not possible, can one get it from the Controller and pass it as a variable without doing yet another validation?
I don't think I need to post the FormTypes because they're long, nested and might only confuse you. However, this is an oversimplified version of the parent form:
class CompanyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('address')
->add('representedBy')
->add('category')
->add('phone')
->add('member', new MemberType())
->add('contacts', new ContactType())
->add('notes', new NoteType())
// and a couple more embedded form types.
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\FooBundle\Entity\Company',
'cascade_validation' => true
));
}
/**
* #return string
*/
public function getName()
{
return 'app_company';
}
}
If anybody has a better idea or solution, I would really appreciate it.
First you can use tabs in two different ways:
a) With javascript. All the content of the tabs are loaded once and can be found in the source of the page. All tab-content is hidden except one.
b) With links and PHP. In this case every tab is another webpage with another URL.
(hopefully you understand the difference)
I always use the second method for my advanced forms. Thus for each page i only add a part of all the formfields in the formtype. For each page i use one validation group too. This is already enough to EDIT existing entities.
But a problem is a new Entity. You might want to avoid partly filled entities in your database, thus you need to validate and then store every 'step' in the session and after the user has finished last step (and validation was okay) you might want to store all the form-fields in one time into the database.
This method is used by the craueformflowbundle.
To get a part of your formfields simply use a switch in your formType or create a formType for each step.
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CompanyType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
switch ($options['flow_step']) {
case 1:
$builder
->add('company')
->add('origin')
;
break;
case 2:
$builder
->add('contactPerson', NULL, array('label' => 'Volledige naam'))
->add('email', 'email', array('label' => 'Email'))
->add('telephone', NULL, array('label' => 'Telefoonnummer'))
;
break;
}
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Company',
'flow_step' => 1
));
}
/**
* #return string
*/
public function getName()
{
return 'appbundle_company';
}
}

Symfony Form Component Standalone Form Type Extension

I have a project using some components from Symfony. Namely Twig, Doctrine, and Form.
I would like to modify all form field types to be able to take a new 'suffix' argument when they are created. It seems like this is usually simple in the full Symfony stack and could be done by extending the existing form type. However I'm not sure how to get the form component to load my custom extension when using the Form Component standalone.
Any help would be great, thank you!
Okay, if I understood your question correctly, what you basically want to do, is add new option to your form builder for given type.
index.php - Basically here, we will just create a FormBuilder instance and add one field for testing purpose.
<?php
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension;
$formFactory = Forms::createFormFactoryBuilder()
->getFormFactory()
->createBuilder()
->add('test', 'text', array('customAttribute' => true))
->getForm()
->createView();
If we open the browser right now, we will get nice and big error, telling us that "customAttribute" is unknown option.
So, let's create custom form type! As you saw I named it TextCustomType since I will extends "text" form type.
The Type class:
<?php
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
class TextCustomType extends AbstractTypeExtension {
public function getName() {
return "text";
}
public function getExtendedType() {
return "text";
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setOptional( array('customAttribute') );
$resolver->setDefaults( array('customAttribute' => true) );
}
public function buildView(FormView $view, FormInterface $form, array $options) {
$view->vars['customAttribute'] = $options['customAttribute'];
}
}
Now, we created our custom type, so lets add it to the form factory:
$formFactory = Forms::createFormFactoryBuilder()
->addTypeExtension( new TextCustomType() ) // once the class is loaded simply pass fresh instance to ->addTypeExtension() method.
->getFormFactory()
->createBuilder()
->add('test', 'text', array('customAttribute' => true))
->getForm()
->createView();
Refresh your browser, and you should be good to go! Hope you got the idea.
Updated as per OP's suggestion.
The answer is pretty simple! It was just a matter of looking in the right place. The FormFactoryBuilder is the key:
use Symfony\Form\Component\Form\Forms;
$form = Forms::createFormFactoryBuilder()
->addTypeExtension(new MyExtension())
->getFormFactory()
->create();
This $form variable now knows about my new 'suffix' property.

Symfony: How to hide form fields from display and then set values for them in the action class

I am fairly new to symfony and I have 2 fields relating to my table "Pages"; created_by and updated_by. These are related to the users table (sfGuardUser) as foreign keys. I want these to be hidden from the edit/new forms so I have set up the generator.yml file to not display these fields:
form:
display:
General: [name, template_id]
Meta: [meta_title, meta_description, meta_keywords]
Now I need to set the fields on the save. I have been searching for how to do this all day and tried a hundred methods. The method I have got working is this, in the actions class:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form_params = $request->getParameter($form->getName());
$form_params['updated_by'] = $this->getUser()->getGuardUser()->getId();
if ($form->getObject()->isNew()) $form_params['created_by'] = $this->getUser()->getGuardUser()->getId();
$form->bind($form_params, $request->getFiles($form->getName()));
So this works. But I get the feeling that ideally I shouldnt be modifying the web request, but instead modifying the form/object directly. However I havent had any success with things like:
$form->getObject()->setUpdatedBy($this->getUser()->getGuardUser());
If anyone could offer any advice on the best ways about solving this type of problem I would be very grateful.
Thanks,
Tom
After processing and saving the form you could set those fields on the object and re-save:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()));
if ($form->isValid())
{
$page = $form->save();
$user = $this->getUser()->getGuardUser();
$page->setUpdatedBy($user);
if (empty($page->created_by))
{
$page->setCreatedBy($user);
}
$page->save();
$this->getUser()->setFlash('notice', 'Successfully saved page.');
$this->redirect('#homepage');
}
}
There's also a Doctrine extension called Blameable that automatically sets edited_by and created_by fields on specified models. The Doctrine website is undergoing some reorganization but here is the cached page for the extension.
To process your form create a new object, set the fields then save.
$article = new Article();
$article->setName($request->getParameter($form->getName());
$article->setDescription($request->getParameter($form->getDescription());
$article->setMetaKeywords($request->getParameter($form->getMetaKeywords());
$article->save();
What you want to do is customize your form and unset the 'created_at' and 'updated_at' pieces of the form in configure
class SampleForm extends BaseSampleForm
{
public function configure()
{
unset(
$this['created_at'],
$this['updated_at']
);
}
}
Then they won't show up in the form and will get the values setup by the "Timestampable" behavior before being saved
http://stereointeractive.com/blog/2010/04/07/symfony-forms-hide-created_at-updated_at-columns/