Im trying to use the built in dropdown HTML helper, but i cant find how to add the id="idvalue"
The documentation give this example,
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'));
When i try the following code, i get errors
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'id' => 'idvalue');
Im using Laravel 4.
Any help would be greatly appreciated.
Cheers,
From the source code of FormBuilder.php:
/**
* Create a select box field.
*
* #param string $name
* #param array $list
* #param string $selected
* #param array $options
* #return string
*/
public function select($name, $list = array(), $selected = null, $options = array());
So you should call
echo Form::select('size', array('key' => 'value'), 'default', array('id' => 'ID_HERE'));
The easy answer
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'L', array('id' => 'idvalue'));
fourth parameter must be an array
{!! Form::select('designation_id', $designations, old('designation_id'),
['class' => 'form-control', 'required', 'id' => '#designation']) !!}
you can add like this
Related
In web.php i have this Route::resources method
Route::resources([
'products' => App\Http\Controllers\ProductsController::class,
'categories' => App\Http\Controllers\CategoriesController::class,
'page-info' => App\Http\Controllers\PageInfoController::class,
]);
How can I specify only index,edit and update for 'page-info' route? and how to add name to each route?
I know that I can do it like this
Route::resource('products', ProductsController::class);
Route::resource('page-info', PageInfoController::class)->only([
'index', 'edit', 'update'
]);
//itd...
but I like the array one resources and thought it is possible too
You can't do what you want, if the documentation does not explicitly say you can or not, you can always have a look at the source code.
So, source code for Laravel 8.x has:
/**
* Register an array of resource controllers.
*
* #param array $resources
* #param array $options
* #return void
*/
public function resources(array $resources, array $options = [])
{
foreach ($resources as $name => $controller) {
$this->resource($name, $controller, $options);
}
}
So, you can do
Route::resources([
'products' => App\Http\Controllers\ProductsController::class,
'categories' => App\Http\Controllers\CategoriesController::class,
'page-info' => App\Http\Controllers\PageInfoController::class,
], $options);
But the code shows that it will share the options for all the resources to be created, so the answer is a no, you can't (at least what I am looking at the source code).
Before passing the data to Controller, the data is being added :
formData.push({"name":"channels","value":JSON.stringify(channels)});
Cause of this even when no data is present, its passed like
'channels' => '[]'
Now the issue is when I try to validate this in validator, I cannot use
'channels' =>'required',
'channels.*' =>'required|exists:channels,id',
How do validate the above data? Don't want to convert the format as its a working system. Any suggestions are appreciated. Thanks.
Updated for Request All Params:
'_token' => 'DjqgmNab0o3ifrVrSvHh6dM5vxLP7tZDc47pq05r',
'startdate' => '05 Sep 2018',
'years' => NULL,
'months' => NULL,
'enddate' => NULL,
'addChannel' => NULL,
'offerRuns' => 'UL',
'numberOfRuns' => NULL,
'limitPeriod' => 'FP',
'licenseAudioTrack' => '1',
'amount' => NULL,
'include_materials_costs' => '1',
'include_withholding_taxes' => '1',
'paymentTermsType' => 'US',
'termsAndConditionDescription' => NULL,
'document_s3_url' => NULL,
'file' => NULL,
'fileSize' => NULL,
'materialSpecificationDescription' => NULL,
'note' => NULL,
'countries' => '[]',
'platforms' => '["1","2","3","4","5","6","7","8","9"]',
'platforms-exclusive' => '[]',
'platforms-non-exclusive' => '[]',
'platforms-holdback' => '[]',
'channels' => '[]',
'languages' => '[["56","AL",1,"seller"]]',
'currencySelectedTerm' => 'EP',
'currencyId' => '1',
'paymentTerms' => '[]'
Check the present validation rule. It states:
present
The field under validation must be present in the input data but can
be empty.
Also look into sometimes rule:
In some situations, you may wish to run validation checks against a
field only if that field is present in the input array. To quickly
accomplish this, add the sometimes rule to your rule list
https://laravel.com/docs/5.7/validation#conditionally-adding-rules
As I understood channels is passed as JSON string & required validator is not working because it is not an empty string.
You can create a custom validator to validate empty JSON string & use it.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class JsonRequired implements Rule
{
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return ! empty(json_decode($value, true));
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The :attribute is required.';
}
}
And use it as 'channels' =>'new JsonRequired'.
If you only need once throughout your application, you may use a Closure instead of a rule object.
Laravel custom validation
You can use json_decode for data first and then apply validations
public function store(Request $request)
{
$request_data = $request->all();
foreach($request_data as $key=>$value)
{
$request_data[$key] = json_decode($value);
}
// And then pass data in validator rules
$rules = [
// All rules here
];
$validator = Validator::make($request_data, $rules);
// other code
}
I have a problem with my FormType. I want to display data and thanks to the querybuilder make a distinction. Problem when I call my method with a -> select ('t.nomVern') I have "Warning: spl_object_hash () expects parameter 1 to be object, string given" as an error message.
I do not understand why.
My FormType ObservationType:
<?php
namespace ObservationBundle\Form;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;
use ImportBundle\Repository\TaxrefRepository;
use ImportBundle\Entity\Taxref;
class ObservationType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('date', DateType::class, array(
'widget' => 'single_text',
'html5' => false,
'attr' => array(
'placeholder' => 'Choisir la date de l\'observation',
)
))
->add('latitude', TextType::class, array(
'attr' => array(
'placeholder' => 'Latitude ex : 31.85322'
)
))
->add('longitude', TextType::class, array(
'attr' => array(
'placeholder' => 'Longitude ex : 33.55555'
)
))
->add('nombre', IntegerType::class)
->add('imageFile', VichImageType::class, array(
'required' => false,
'allow_delete' => false, // not mandatory, default is true
'download_link' => false, // not mandatory, default is true
'attr' => array(
'placeholder' => 'Votre image'
)
))
->add('valide', HiddenType::class)
->add('commentaire', HiddenType::class)
->add('gpsAffiche', HiddenType::class)
->add('meteo', HiddenType::class)
->add('saison', HiddenType::class)
->add('typeSaisie', HiddenType::class)
->add('precipitation', HiddenType::class)
->add('periode', HiddenType::class)
->add('environnement', HiddenType::class)
->add('sensibilite', HiddenType::class)
->add('comportement', HiddenType::class)
->add('species', EntityType::class, array(
'label' => 'Espèce observée :',
'class' => 'ImportBundle\Entity\Taxref',
'choice_label' => 'nomVern',
'query_builder' => function(TaxrefRepository $qb){
return $qb->distinctTaxref();
}
))
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ObservationBundle\Entity\Observation'
));
}
/**
* #return string
*/
public function getBlockPrefix()
{
return 'observationbundle_observation';
}
}
And my repository :
<?php
namespace ImportBundle\Repository;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class TaxrefRepository extends EntityRepository
{
/**
* Pagination liste des especes
* #param int $page
* #param int $max
* #return Paginator
*/
public function findByPage($page = 1, $max = 8)
{
if(!is_numeric($page)) {
throw new \InvalidArgumentException(
'$page must be an integer ('.gettype($page).' : '.$page.')'
);
}
if(!is_numeric($page)) {
throw new \InvalidArgumentException(
'$max must be an integer ('.gettype($max).' : '.$max.')'
);
}
$dql = $this->createQueryBuilder('t');
$dql->orderBy('t.id', 'DESC');
$firstResult = ($page - 1) * $max;
$query = $dql->getQuery();
$query->setFirstResult($firstResult);
$query->setMaxResults($max);
$paginator = new Paginator($query);
if(($paginator->count() <= $firstResult) && $page != 1) {
throw new NotFoundHttpException('Page not found');
}
return $paginator;
}
/**
* #return \Doctrine\ORM\QueryBuilder
*/
public function distinctTaxref()
{
return $this
->createQueryBuilder('t')
->select('t.nomVern')
->distinct(true)
->orderBy('t.nomVern', 'ASC');
}
}
Thank you in advance for your help and sorry for my bad english :/
Try this part of code
return $this
->createQueryBuilder('t')
->select(array('t.nomVern'))
->distinct(true)
->orderBy('t.nomVern', 'ASC');
I believe that, since you're using EntityType, Symfony expects to have an array of objects, whereas you select a single column which produces an array of strings.
Can you try selecting an object as a whole:
return $this
->createQueryBuilder('t')
->select('t')
->distinct(true)
->orderBy('t.nomVern', 'ASC');
Does this work?
I have a form containing a field that expects an integer. This is the field definition in the form type entity definition:
/**
* #ORM\Column(type="integer", nullable=true)
* #Assert\Type(type="integer", message="Number of pieces must be a number.")
* #Assert\GreaterThanOrEqual(value=1, message="Number of pieces cannot be lower than 1.")
*/
protected $numberOfPiecesSent;
The relevant form builder looks like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('numberOfPiecesSent', 'integer', array('label' => 'Number of pieces sent:', 'required' => false));
}
When I submit the form with a non-numerical value in the field (say, 'aaa'), it just saves the form and leaves the field numberOfPiecesSent NULL in the database instead of failing on validation. I also tried to make the field non-NULL, but that didn't help. Any ideas why this isn't working, please?
I've just tested and this works fine. You can add constraints into your property below. You can remove NotBlank as well. Modify as you wish.
entity
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $numberOfPiecesSent;
form
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Range;
->add(
'numberOfPiecesSent',
'integer',
[
'constraints' => [
new NotBlank(
[
'message' => 'The numberOfPiecesSent is required.'
]
),
new Range(
[
'min' => 1,
'minMessage' => "The numberOfPiecesSent must contain at least {{ limit }}"
]
)
]
]
)
UPDATE
use Symfony\Component\Validator\Constraints\Regex;
->add(
'name',
'text',
[
'constraints' => [
new Regex(
[
'pattern' => "/^[0-9]+$/"
]
)
]
]
)
OR
use Symfony\Component\Validator\Constraints\Regex;
->add(
'name',
'integer',
[
'constraints' => [
new Regex(
[
'pattern' => "/^[0-9]+$/"
]
)
]
]
)
Have you tried to make field not null with:
#ORM\Column(type="integer", nullable=false)
or did you also tried with the assert NotNull ?
http://symfony.com/fr/doc/current/reference/constraints/NotNull.html
I am trying to programatically add products to my drupal commerce store. So far I have been able to add products that contain basic information ( such as sku, title, and price ). How would I be able to add field data, such as images and other field types, using drupal's api.
The code I used to add the products is derived from the commerce_examples/product_example module.
<?php
/**
* #file product_example.module
* Demonstrates pricing hooks, etc.
*/
/**
* Implements hook_menu().
*
* Simply presents a page that will explain what this module is for.
* hook_menu() has nothing to do with the checkout page functionality.
*/
function product_example_menu() {
$items['commerce_examples/product_example'] = array(
'title' => 'Product Example',
'page callback' => 'drupal_get_form',
'page arguments' => array('product_example_info_page'),
'access callback' => TRUE,
);
return $items;
}
/**
* This form provides a way to interact with some of the example functions
* provided here.
*/
function product_example_info_page($form, &$form_state) {
$form['explanation'] = array(
'#type' => 'item',
'#markup' => t('This example demonstrates product creation and manipulation.'),
);
$form['product_creation'] = array(
'#type' => 'fieldset',
'#title' => t('Please create a product for use with this example'),
);
$types = commerce_product_types();
$form['product_creation']['product_type'] = array(
'#type' => 'select',
'#title' => t('Product type for product to be created'),
'#options' => drupal_map_assoc(array_keys($types)),
);
$form['product_creation']['title'] = array(
'#title' => t('Product title'),
'#type' => 'textfield',
'#default_value' => t('A dummy product for use with product_example'),
);
$form['product_creation']['price'] = array(
'#title' => t('Product price'),
'#type' => 'textfield',
'#description' => t('A price in decimal format, without a currency symbol'),
'#default_value' => '100.00',
);
$form['product_creation']['product_creation_submit'] = array(
'#type' => 'submit',
'#value' => t('Create product'),
'#submit' => array('product_example_product_creation_submit')
);
return $form;
}
/**
* Submit handler for creating a product.
*/
function product_example_product_creation_submit($form, &$form_state) {
$extras = array(
'sku' => 'product_example_' . drupal_hash_base64(microtime()),
'status' => TRUE,
'uid' => $GLOBALS['user']->uid,
'title' => $form_state['values']['title'],
);
// Use the product example's creation function to create a product.
$product_id = product_example_create_product($form_state['values']['product_type'], $form_state['values']['price'], $extras);
drupal_set_message(t('Created sample product with title !title and sku !sku', array('!title' => l($extras['title'], 'admin/commerce/products/' . $product_id), '!sku' => $extras['sku'])));
}
/**
* Create a product programmatically.
*
* This is stolen shamelessly from commerce_bpc. Thanks for the help here!
*
* #param $product_type
* (string) The name of the product type for which products should be created.
* #param $price
* Decimal amount of price. If additional fields need to be populated they
* can be populated in exactly the same way as the commerce_price field.
* #param $extras
* An array for the values of 'extra fields' defined for the product type
* entity, or patterns for these. Recognized keys are:
* - status
* - uid
* - sku
* - title
* Note that the values do NOT come in the form of complex arrays (as they
* are not translatable, and can only have single values).
* #return
* The ID of the created product.
*/
function product_example_create_product($product_type, $price, $extras) {
$form_state = array();
$form_state['values'] = array();
$form = array();
$form['#parents'] = array();
// Generate a new product object
$new_product = commerce_product_new($product_type);
$new_product->status = $extras['status'];
$new_product->uid = $extras['uid'];
$new_product->sku = $extras['sku'];
$new_product->title = $extras['title'];
$new_product->created = $new_product->changed = time();
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
'amount' => $price * 100,
'currency_code' => commerce_default_currency(),
)));
$form_state['values']['commerce_price'] = $price;
// Notify field widgets to save their field data
field_attach_submit('commerce_product', $new_product, $form, $form_state);
commerce_product_save($new_product);
return $new_product->product_id;
}
Using the same format the examples uses to add price data:
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
'amount' => $price * 100,
'currency_code' => commerce_default_currency(),
)));
I was able to add other field data, however I am still having trouble adding data to the field_productimage field that all commerce products come with by default.
I can suggest you about other fields data such as extra info related to product. You can add these fields to the product type from the UI or if you are creating product type programmatically then also you can do the same.
Add fields in your form to collect the data e.g -
$form['product_creation']['values'] = array(
'#title' => t('Some data'),
'#type' => 'textfield',
'#description' => t('Dummy data'),
);
Get those data in your function product_example_create_product() by $form_state().
Add them to $new_product object like
$new_product->field_name['und'][0]['value'] = $extras['values'];
Save the product, just like you are doing.
For the image, you will have to follow the method of file attachment. Like -
$file_path = drupal_realpath('image/product_image.png');
$file = (object) array(
'uid' => 1,
'uri' => $file_path,
'filemime' => file_get_mimetype($file_path),
'status' => 1,
);
// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');
$new_product->product_image[LANGUAGE_NONE][0] = (array)$file;