Laravel validation for numbers with spaces - laravel-5.3

Laravel has a validation for some input types i have searched validation rule for numbers and it may contains some whitespaces or may not be. I have used validation rules of numeric and integer but its not allowing whitespaces.
And i have custom error message displayer with class. i need to show validator error message in that message but i got output error message as like below
How can i display error message of validator normally and my code is
$validator = Validator::make($request->all(), [
'header_logo' => 'image|mimes:jpeg,png,jpg,svg',
'contact_number' => 'numeric',
'contact_email' => 'email',
'footer_logo' => 'image|mimes:jpeg,png,jpg,svg',
'enquiry_email' => 'email',
'website' => 'active_url',
'vat' => 'integer',
'sale_mobile' => 'numeric',
'sale_email' => 'email'
]);
if ($validator->fails()) {
return back()->withInput()->with(['admin' => $validator->errors(), 'class' => 'danger']);
}

You can use https://laravel.com/docs/5.3/validation#rule-regex
ex : 'regex:/[0-9 ]+/'
or https://laravel.com/docs/5.3/validation#custom-validation-rules

Related

Symfony 4.2 event POST_SUBMIT is returning null

Im doing 3 forms in Symfony 4.2.5 all with the same code when load states and cities (estados and municipios) but only this form is making me crazy because has the same code that all but doesnt work it always return null in "municipio", and when I print $request it has municipio=1 but in $form->isValid() says that municipio is null and it started when I added FormEvents
Please if someone could help me I'll be grateful, I inspected all my code but this is where its break.
$builder->get('estado')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$estado = $event->getForm()->getData();
if (null == $estado) {
$event->getForm()->getParent()->add('municipio', EntityType::class, [
'class' => 'App\Entity\Municipio',
'required' => true,
'placeholder' => '== Selecciona un municipio 1==',
'choices' => []
]);
} else {
$event->getForm()->getParent()->add('municipio', EntityType::class, [
'class' => 'App\Entity\Municipio',
'required' => true,
'placeholder' => '== Selecciona un municipio 2 ==',
'choices' => $estado->getMunicipios()
]);
}
}
);
I had duplicated my field, one in buildForm when add and other in the event and cause bad behaviour.
Symfony dont say that we can not add a field more than 1 time and no error is showing until I needed submit the form and my field was not recognized and always had null value.
I just deleted $builder->add('municipio') and all work fine.

Symfony2 DateTime null accept

So, I want to be able send a null option to my DOB field.
Here is my form builder:
->add('birthDate', DateType::class, array(
'widget' => 'single_text',
'format' => 'yyyy-MM-dd'))
And here is those field in my entity
/**
* #ORM\Column(
* type="date",
* nullable=true
* )
* #JMS\Groups("single")
*
* #var \DateTime
*/
protected $birthDate;
When I`m trying to send a null I got an error msg
Expected argument of type "DateTime", "NULL" given
any ideas?
CRITICAL - Uncaught PHP Exception Symfony\Component\PropertyAccess\Exception\InvalidArgumentException: "Expected argument of type "DateTime", "NULL" given" at /var/www/server.local/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php line 253
$type = $trace[$i]['args'][0];
$type = is_object($type) ? get_class($type) : gettype($type);
throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given', substr($message, $pos, strpos($message, ',', $pos) - $pos), $type));
}
}
In this case, the problem was caused by PHP type hinting.
If you use type hinting (for instance setBirthDate(\DateTime $value)) then PHP forces you that you actually provide a DateTime object. Obviously, null is not such an object. To resolve this problem, it is possible to give $value a default value like this: setBirthDate(\DateTime $value = null).
This is documented behavior and explained in the PHP Documentation (http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration).
Relevant passage:
To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.
The problem occurs due type-hinted setter as it is mentioned in the comments. There are two solutions:
1. Use 'by_reference' => true on your form:
$builder->add(
'birthDate',
DateType::class,
[
'widget' => 'single_text',
'format' => 'yyyy-MM-dd',
'by_reference' => true,
]
);
2. Let your setter accept null:
public function setBirthDate(\DateTime $value = null)
{
.....
}
Don't pass any values to it. Make the field not required by doing this:
->add(
'birthDate',
DateType::class,
array(
'required' => false,
'widget' => 'single_text',
'format' => 'yyyy-MM-dd'
)
)
I have been using DOB field in my project. Try this.
My ORM file looks like this <field name="dob" type="date" column="dob" nullable="true"/>
->add('dob','birthday',array(
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'required' => false,
'attr' => array('class' => 'datepicker',
'data-provide' => 'datepicker','data-date-format' => 'dd-mm-yyyy')
))

Symfony2, Sonata, FormMapper, add hidden field to be handled in PrePersist/PreUpdate

I actually did some tricks so i could be able to persist a user if its ID is passed by an url parameter. (Custom action from user list).
/admin/se/api/bundle/create?user=7
I actually could not find how to send the user entity returned by a findByOne(array('id' => $user_id)) so i guess i'll need to pass the $user_id through a hidden field and handle its value in a PrePersist
Otherwise passing the id that way
->add('user', 'hidden', array('data' => $user_id))
will return an error :
This value is not valid.
Symfony\Component\Validator\ConstraintViolation
Object(Symfony\Component\Form\Form).children[user] = 7
Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
Compound forms expect an array or NULL on submission.
This is my first attempt that is not working :
$container = $this->getConfigurationPool()->getContainer();
$request = $container->get('request');
$user_id = $request->get('user');
if(!empty($user_id)){
$em = $this->getModelManager()->getEntityManager($this->getClass());
$user = $em->getRepository('ApiBundle:User')->findOneBy(array('id' => $user_id));
if($user){
$formMapper
->with('User', array('description' => '<strong>User : </strong>'.$user->getDisplayName()))
->add('user', 'hidden', array('data' => $user_id))
// this of course doesn't work as explained above. How can i have my own hidden input not related to any property
->end();
}
So how would i do that? Any better solution is welcomed.
Well this is the best trick i found. I wish 'sonata_type_model_hidden' has more options. I guess i could do my own custom field to be able to do that. But i'm not sure how and anyway this solution is fast to implement.
$formMapper
->with('Guide', array('description' => '<strong>Guide : </strong>'.$guide->getDisplayName()))
->add('guide', 'sonata_type_model_autocomplete', array(
'property' => array('firstname', 'lastname', 'username', 'email'),
'data_class' => null, // IMPORTANT
'data' => $guide,
'attr' => array('class' => 'sonata-autocomplete-hidden'), // custom class
'label_attr' => array('class' => 'sonata-autocomplete-hidden'), // custom class
)
)
->end();
To hide the field :
.sonata-autocomplete-hidden{
display:none;
}
If you have any better solutions, you're welcome.

ManyToMany nullable not allowed

I have a scenario like this:
tracks ManyToMany instruments
I create the form in this way:
$builder
->add('instruments', 'entity_hidden', array(
'attr' => array('class' => 'one_req'),
'label' => 'form.instrument',
'translation_domain' => 'label',
'required' => false,
'class' => 'Acme\DemoBundle\Entity\Instrument'
))
"hidden_entity" is given by a custom transformer that you can find here: gist
although I believe that is not the problem.
The problem is that the user may not even choose any instrument (such asamong other specified with "required" => false).
When I go to save my returns this error:
Neither the property 'instruments' nor one of the methods 'setInstruments()',
'__set()' or '__call()' exist and have public access in
class 'Acme\DemoBundle\Entity\SoundtrackVersion'.
I do not understand why ..
Where am I doing wrong?
It sounds very obvious, but error can not lie. Check that Acme\DemoBundle\Entity\SoundtrackVersion entity has property instruments and methods setInstruments() and getInstruments().

Please Explain Drupal schema and drupal_write_record

1) Where is the best place to populate a new database table when a module is first installed, enabled? I need to go and get some data from an external source and want to do it transparently when the user installs/enables my custom module.
I create the schema in {mymodule}_schema(), do drupal_install_schema({tablename}); in hook_install. Then I try to populate the table in hook_enable using drupal_write_record.
I confirmed the table was created, I get no errors when hook_enable executes, but when I query the new table, I get no rows back--it's empty.
Here's one variation of the code I've tried:
/**
* Implementation of hook_schema()
*/
function ncbi_subsites_schema() {
// we know it's MYSQL, so no need to check
$schema['ncbi_subsites_sites'] = array(
'description' => 'The base table for subsites',
'fields' => array(
'site_id' => array(
'description' => 'Primary id for site',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
), // end site_id
'title' => array(
'description' => 'The title of the subsite',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '',
), //end title field
'url' => array(
'description' => 'The URL of the subsite in Production',
'type' => 'varchar',
'length' => 255,
'default' => '',
), //end url field
), //end fields
'unique keys' => array(
'site_id'=> array('site_id'),
'title' => array('title'),
), //end unique keys
'primary_key' => array('site_id'),
); // end schema
return $schema;
}
Here's hook_install:
function ncbi_subsites_install() {
drupal_install_schema('ncbi_subsites');
}
Here's hook_enable:
function ncbi_subsites_enable() {
drupal_get_schema('ncbi_subsites_site');
// my helper function to get data for table (not shown)
$subsites = ncbi_subsites_get_subsites();
foreach( $subsites as $name=>$attrs ) {
$record = new stdClass();
$record->title = $name;
$record->url = $attrs['homepage'];
drupal_write_record( 'ncbi_subsites_sites', $record );
}
}
Can someone tell me what I'm missing?
If ncbi_subsites_get_subsites() is not in the .install file, you need to include whatever file its in with your module. Otherwise, it's returning nothing, in which case try dumping $subsites and exiting.
I think the answer is that drupal_write_record is not meant for install or enable hooks. I think when enabling or installing, you have to write SQL. That is the impression I am getting from reading some posts that mention that the schema is not available in these hooks.
First of all (assuming Drupal 6), drupal_write_record() cannot be called from hook_install() because Drupal would not find the database schema defined from the module, which is still going to be installed, and enabled.
Instead you need to use db_query() function. (the comments are speaking of a way to include default data by prviding it to hook_schema() serialized, but i've found no documentation on this.)
However, would you be using (the development version of) Drupal 7, you want to look at the db_insert() function instead.

Resources