CSV Upload - mime types - symfony1

Hi I'm trying to upload a CSV file using the following form code:
$this->widgetSchema ['file'] = new sfWidgetFormInputFile();
$this->setValidator('file', new sfValidatorFile(array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir') . '/properties/csv',
'mime_categories' => array('csv' => array('text/csv', 'application/csv', 'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel')),
'mime_types' => 'csv'
)));
In my action I have:
if($request->isMethod('post'))
{
$propertyCsvForm->bind($request->getParameter($propertyCsvForm->getName()), $request->getFiles($propertyCsvForm->getName()));
if($propertyCsvForm->isValid())
{
$this->getUser()->setFlash('success-csv', 'The CSV was successfully imported.');
} else {
$this->getUser()->setFlash('error-csv', 'The CSV could not be imported.');
}
}
When I try to upload a CSV I always get an error, which is the mime type is incorrect
Invalid mime type (text/plain).
Any ideas why?
Thanks

I had the same problem and I solved it creating a postValidator in which I get the path of the file and I do a test to check if is a csv file or not and it works fine
class sfValidatorCSV extends sfValidatorSchema
{
protected function configure($options = array(), $messages = array())
{
parent::configure($options, $messages);
}
protected function doClean($values)
{
$file = $values['file'];
if(empty($file)==false)
{
$filename = $file->getOriginalName();
$path = pathinfo($filename);
if($path['extension']!="csv")
{
throw new sfValidatorError($this, 'Invalid extension.');
}
}
}
}
And you call it at the end of your form like this:
$this->mergePostValidator(new sfValidatorCSV());

Related

How to call an error action from redux_epic?

I'm trying to do like so:
Stream<dynamic> searchEpic(
Stream<PerformSearchAction> actions,
EpicStore<AppState> store,
) {
return actions.asyncMap((action) => fetchPost()
.then((results) => SearchResultsAction(results['title']))
.catchError((error) => SearchErrorAction(error.message)));
}
However I get the follow error message:
type 'SearchErrorAction' is not a subtype of type "FutureOr SearchResultsAction "
I just needed to define that the type I wanted to work through the pipe as dynamic, like so:
Stream<dynamic> searchEpic(
Stream<PerformSearchAction> actions,
EpicStore<AppState> store,
) {
return actions.asyncMap<dynamic>((action) => fetchPost()
.then<dynamic>((results) => SearchResultsAction(results['title']))
.catchError((error) => SearchErrorAction(error.message)));
}

Symfony Error when loading a Profile Form

I'm currently getting this error when trying to load an edit form for my Profile entity.
The form's view data is expected to be an instance of class AppBundle\Entity\Profile, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of AppBundle\Entity\Profile.
I was Wondering if anyone knows how to fit this. I'm using a Profile controller and the User and Profile have a OneToOne relationship with each other.
Here is my code for the Profile controller that loads that form
/**
* #Route("/profile/edit", name="profile_edit")
*/
public function editAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$profileRepository = $em->getRepository(Profile::class);
$user = $this->getUser();
$profile = $profileRepository->getProfileByUserId($user->getId());
$form = $this->createForm(ProfileType::class, $profile);
$form->handlerequest($request);
if( $form_.isSubmitted() && $form->isValid()) {
$firstname = $form->get('firstname')->getData();
$lastname = $form->get('lastname')->getData();
$description = $form->get('description')->getData();
$profile->setFirstname($firstname);
$profile->setLastName($lastname);
$profile->setDescription($description);
$em->persist($profile);
$em->flush();
$this->addFlash('flash-profileeditted', 'You\'ve successfully updated your profile.');
$this->redirectToRoute('profile_page');
}
return $this->render('profile/edit.html.twig', ['form' => createForm(), 'profile' => $profile]);
}
And here is my ProfileType::class
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', TextType::class, [ 'label' => 'Firstname', 'attr' => ['class' => 'form-control']])
->add('lastname', TextType::class, ['label' => 'Lastname', 'attr' => ['class' => 'form-control']])
->add('description', TextareaType::class, ['label' => 'In Your Own Words', 'attr' => ['class' => 'form-control']])
->add('user')
->add('submit', SubmitType::class, ['label' => 'Edit Profile', 'attr' => ['class' => 'btn btn-info']]);
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Profile'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_profile';
}
Not Sure what else to include here, hopefully everything is ok and the solution can be found within this code.
I should also point out that I am using FOSUserBundle.
Thanks in advance,
Ok. I finally found out what was happening. I was using the Profile Repository to find a user by their id, but that was returning an array. So what I had to do is use this code:
$profile = $profileRepository->findOneByUser($user->getId());
This actually returns the Object as an AppBundle\Entity\Profile object which can then be used to populate the form.

Lithium Framework: Different URL multi language site

I want to get different URLs for different languages.
For example:
http://www.example.com/en/users/create
http://www.example.com/es/usuarios/crear
I have g11n enabled and I tried this:
Router::connect('/users/create',array('controller'=>'User','action'=>'add'));
Router::connect('/usuarios/crear',array('controller'=>'User','action'=>'add'));
But,... in header.html.php where I have the menu code:
<ul id="nav">
<li class="menu-item ">
<?php echo $this->html->link('New User','/user/add') ?>
</li>
</ul>
I need a function that returns the link:
...
when the current language is Spanish.
or
...
when the current language is English.
Sorry for my english...
Edit:
I have solved the problem overriding \lithium\template\helper\Html class.
<?php
namespace app\extensions\helper;
use lithium\core\Environment;
function getLanguage($locale)
{
$res = array_shift(explode('_', $locale));
if(!$res)return '?';
else return $res;
}
class CustomHtml extends \lithium\template\helper\Html {
private static $_mapping = array(
'Users' => array(
'Add' => array(
'es' => '/es/usuarios/crear',
'en' => '/en/users/create',
)
)
);
/**
* Override Helper::link
*/
public function link($title, $url = null, array $options = array()) {
if(is_array($url))
{
if(key_exists('controller', $url))
{
$controller = $url['controller'];
if(key_exists('action', $url))
{
$action = $url['action'];
$locale = key_exists('locale', $url) ? $url['locale'] : getLanguage(Environment::get('locale'));
$new_url = $this->_matchUrl($controller, $action, $locale);
if($new_url)
{
return parent::link($title, $new_url,$options);
}
else
{
die('?');
}
}
}
}
return parent::link($title,$url,$options);
}
private function _matchUrl($controller, $action, $locale)
{
if(isset(self::$_mapping[$controller][$action][$locale]))
{
return self::$_mapping[$controller][$action][$locale];
}
return null;
}
}
Now in template I can use this function to get the correct link:
<?php echo $this->CustomHtml->link('Create user',array('controller'=>'Users', 'action' => 'add')) ?>
I am sure it isn't the best solution. But it works...
Here is an example that includes locale-based routing: https://gist.github.com/nateabele/1512502

Front End post form either sets a thumbnail or give me ID, I need both

I have a WP front end post form that I have made for my website, the Idea was to make it so artists can post up their own mixtape submissions!
So far I have managed to get the form to either use the image uploaded as the featured image OR give me the images ID so I can put it in the post content, the problem is I need both! I need the image automatically set as the thumbnail for the post and I need the ID so I can set the form to automatically put the image where I want it in the post!
So far I have located the problem to be this bit of code:
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
// $newupload returns the attachment id
}
}
I say this as, the location of this code is what changes whether I successfully get the ID of the attachment or whether the image is set as the thumbnail.
The whole code is as follows:
function insert_attachment($file_handler,$post_id,$setthumb='false') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
function mixtape_fep($content = null) {
global $post;
// We're outputing a lot of html and the easiest way
// to do it is with output buffering from php.
ob_start(); ?> <?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter the wine name';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter some notes';
}
$cover_id = get_post_meta($post->ID, 'thumb', true);
$cover = wp_get_attachment_link($cover_id);
$content = $cover.'<br /><br />'.$description;
$tags = $_POST['post_tags'];
// ADD THE FORM INPUT TO $new_post ARRAY
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post' //'post',page' or use a custom post type if you want to
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
// $newupload returns the attachment id of the file that
// was just uploaded. Do whatever you want with that now.
}
}
//SET OUR TAGS UP PROPERLY
wp_set_post_tags($pid, $_POST['post_tags']);
//REDIRECT TO THE NEW POST ON SAVE
$link = get_permalink( $pid );
wp_redirect( $link );
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM
//POST THE POST YO
do_action('wp_insert_post', 'wp_insert_post'); ?>
The issue of assigning the thumbnail and inserting the image was fixed by adding this into the code:
if ( $_FILES ) {
$files = $_FILES['cover'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("cover" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}
}
}
}
and then
set_post_thumbnail( $pid, $newupload );
below the insert post function.

cakePHP passing URLs as a param

I have an ImportController with a function admin_getcontents.
function admin_getcontents($url = null)
{
$contents = json_decode(file_get_contents(($url)),true);
//some stuff
}
Through ajax I call /admin/import/getcontents/ with:
$.get('/admin/import/getcontents/'+ encodeURIComponent($('#urlcheck').val()) ,function(data) {
$('#importtable').html(data);
$('#busy-indicator').fadeOut('high');
});
so I call the page: /admin/import/getcontents/http%3A%2F%2Flocalhost%2Feclipse%2Fanarxeio%2Fexport%2Fcontents%2F
Apache gives me an 404 error. If I call /admin/import/getcontents/1 the page loads correctly. So I figured to pass a ? before the parameter like:
admin/import/getcontents/?http%3A%2F%2Flocalhost%2Feclipse%2Fanarxeio%2Fexport%2Fcontents%2F
Now I don't get a 404 error but $url param in admin_getcontents() is empty. How can I achieve the above?
Thanks
A quick fix would be to triple url encode your url:
// javascript
$.get('/admin/import/getcontents/'+ encodeURIComponent(encodeURIComponent(encodeURIComponent($('#urlcheck').val()))) ,function(data) {
$('#importtable').html(data);
$('#busy-indicator').fadeOut('high');
});
Then url decode it in your php before you use it:
// php
function admin_getcontents($url = null)
{
$url = urldecode(urldecode($url));
$contents = json_decode(file_get_contents(($url)),true);
//some stuff
}
EDIT following comments:
You will need to set up your routing to pass the url parameter. Looking at your setup, it should looking something like:
Router::connect('/admin/import/getcontents/:url', array(
'controller' => 'import',
'action' => 'getcontents',
'admin' => true),
array(
'url' => '(.*)',
'pass' => array('url')
)
);

Resources