How to make valid condition for value tag in laravel 5.7 if field was modified and we have to show new value if field was modified ?
I tried like that with required condition :
(old('common_settings_site_name') ? old('common_settings_site_name') : ( isset($common_settings_site_name) ?$common_settings_site_name : '' ) ),
it is good, bur not n case when field with existing value was cleared, then original value(not old - clear) is shown.
Like text field had some text “Value”
The field was cleared.
submitting form original field would be shown not empty string as I exepected ?
How to fix it ?
Thanks!
Look at definition of old :
/**
* Retrieve an old input item.
*
* #param string $key
* #param mixed $default
* #return mixed
*/
function old($key = null, $default = null)
{
return app('request')->old($key, $default);
}
You can use 2nd parameter for old method with your var.
Related
We use a CMS, Fuel, built on Codeigniter, and use the redirect function often. I was wondering if there is a way to use probability with this function so that half (or whatever amount we set) the time it redirects to one page and half the time to another.
In general we will create a page with a redirect that looks like this:
<?=redirect('https://subdomian.onanotherserver.com/asdf')?>
We would love to make it looks similar:
<?=probabilityRedirect(0.5, 'https://subdomian.onanotherserver.com/asdf', 'https://subdomian.onanotherserver.com/jkl')?>
What would be the best way to go about this? Can we build off the redirect or just write a new function?
I would make a new function. Probably adding this to url_helper.php makes it the easiest to implement. Could be a stand-alone helper too but then you have to be certain url_helper is loaded.
if(!function_exists('randomRedirect'))
{
/**
* Randomized Header Redirect
*
* #param int $seed value optional
* #param array $list an indexed array of URL strings
* #return void
*/
function randomRedirect($seed = NULL, $list)
{
//list needs to be an array
if(!is_array($list OR ! isset($list)))
{
throw new Exception('randomRedirect() requires Array in second parameter');
}
if(!empty($seed))
{
mt_srand($seed);
}
$choice_count = count($list);
redirect($list[mt_rand(0, $choice_count)]);
}
}
Note: I did not test this! Results not guaranteed. :)
Revised code below.
Had some time to experiment with the above which eventually resulted in this.
randomURL_helper.php
<?php
if(!function_exists('p_redirect'))
{
/**
* Randomized Header Redirect
*
* #param array $list an indexed array of URL strings
* #param bool $seed optional when true, the random number generator will be seeded
*
* #return void
*
* Takes a list of URL strings in an array and randomly selects one as the
* input to the CodeIgniter function redirect.
* If you specify the full site URL that link will be built,
* but for local links simply providing the URI segments to the
* controller you want to direct to will create the link.
*
* The function will build the URL based on your config file values.
*
* This function requires the CodeIgniter helper "URL Helper"
* to be loaded using the following code: $this->load->helper('url');
*
* Use this line of code $this->load->helper('randomURL');
* to make p_redirect available to your CodeIgniter application.
*
*/
function p_redirect($list, $seed = FALSE)
{
if(!is_array($list))
{
// $list must be an array
throw new Exception('randomRedirect() requires Array as first parameter');
}
if($seed)
{
list($usec, $sec) = explode(' ', microtime());
$seed_val = (float) $sec + ((float) $usec * 100000);
mt_srand($seed_val);
}
redirect($list[mt_rand(0, count($list) - 1)]);
}
}
Tested it enough to see that it's not completely off-base.
Seems to get the job done. Enjoy!
You can just include it inside a rand 50/50 condition,
<?php
if (mt_rand(0,1)) {
redirect('https://subdomian.onanotherserver.com/asdf')
}
?>
Lets say in my lang/en/general.php there are multiple translation lines for example:
"token" => "This password reset token is invalid.",
"sent" => "Password reminder sent!",
"reset" => "Password has been reset!",
But in my lang/de/general.php these lines are missing.
So later, when I use the Lang::get('general.token') or simply trans('general.token')
The english version will return
This password reset token is invalid.
And the german (de) version will return
general.token
Is there any way I can handle a 'translation not found' function, like a filter but not creating a special class for it? For example, when a line has no translation, I want to throw an Exception.
Thanks in advance!
In Laravel 4 only, you can use Lang::has() as below, here is the doc
if (\Lang::has('general.token')) {
// line exists.
} else {
// line not exist.
}
In current Laravel versions you can just use trans helper like so:
#if (trans()->has('general.token'))
{{ trans('general.token') }}
#endif
This question is getting a little bit old but as per version 5.8 you can simply check as this :
array_key_exists('your-word-key', trans('your-file'))
or
array_key_exists('your-word-key', trans('your-file.array_key'))
for nested translations
You might want to write a helper similar to the one below to help with fallbacks:
/**
* Makes translation fall back to specified value if definition does not exist
*
* #param string $key
* #param null|string $fallback
* #param null|string $locale
* #param array|null $replace
*
* #return array|\Illuminate\Contracts\Translation\Translator|null|string
*/
function trans_fb(string $key, ?string $fallback = null, ?string $locale = null, ?array $replace = [])
{
if (\Illuminate\Support\Facades\Lang::has($key, $locale)) {
return trans($key, $replace, $locale);
}
return $fallback;
}
Note: The helper only works on PHP 7.1 (which has support nullable types). Adjust it to your PHP version if it's lower than 7.1.
You can create your own TranslationServiceProvider and Translator and override the get() method in translator to throw an exception when the parent::get() returns a translation string that is equal to the translation key that was passed in. Both #lang() and trans() functions call the get() method of the translator.
Seems like a whole lot of trouble only to get another reason for a "Whoops! something went wrong!" on your site. You will only get the exception when the translation is encountered.
Another solution: you can use the barryvdh/laravel-translation-manager package, it has a translation service provider that logs missing translation keys and a web interface for managing translations. It will log missing translation keys per locale and let you edit them through a web interface.
It is simple to setup and easy to modify. So you can replace the logging with throwing an exception.
I have an entity set up like this:
use Symfony\Component\Validator\Constraints as Assert;
...
/**
* #var decimal $amount
* #Assert\Currency
* #ORM\Column(name="amount", type="decimal")
*/
private $amount;
If I submit my form with blank in the amount field nothing happens. Shouldn't my form automatically throw an error or what am I missing?
You need a NotBlank assertion (#Assert\NotBlank) to validate that that field wasn't submitted with empty data. If that passes, then your other assertions should run on any actual data submitted.
I created a module (extends Mage_Core_Model_Abstract) and an admin controller.
When I run this module online translations are going right.
When I run this module as cronjob, everything goes allright but translations are not done, I specified translation file in config.xml in as well frontend as adminhtml.
What I am doing wrong?
I see this is a very old question. I've posted here to future reference and others.
Quick and dirty solution
// Fix unitialized translator
Mage::app()->getTranslator()->init('frontend', true);
just after
$initialEnvironmentInfo = $appEmulation>startEnvironmentEmulation($storeId);
for instance. Or in a foreach loop of your own, which is called via cron/admin. Since you're talking about crons, I assume that you know what you are doing.
The real problem
In Magento 1.9 in Mage_Core_Model_App_Emulation (in app/code/core/Mage/Core/Model/App/Emulation.php), there's this function:
/**
* Apply locale of the specified store
*
* #param integer $storeId
* #param string $area
*
* #return string initial locale code
*/
protected function _emulateLocale($storeId, $area = Mage_Core_Model_App_Area::AREA_FRONTEND)
{
$initialLocaleCode = $this->_app->getLocale()->getLocaleCode();
$newLocaleCode = $this->_getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $storeId);
if ($initialLocaleCode != $newLocaleCode) {
$this->_app->getLocale()->setLocaleCode($newLocaleCode);
$this->_factory->getSingleton('core/translate')->setLocale($newLocaleCode)->init($area, true);
}
return $initialLocaleCode;
}
The $initialLocaleCode != $newLocaleCode seems to be the issue here. When iteration orders/customers/subscribers/*, the locale could stay the same, which then prevents executing the code in the statement. And the locale is thus not set in the Translator (Mage::app()->getTranslator()).
We've yet to fix the issue, but you could change if ($initialLocaleCode != $newLocaleCode) { to if (true) { straight in the core source. Off course, this is ugly. I suggest something like extending the class and then :
/**
* Apply locale of the specified store. Extended
* to fix Magento's uninitialized translator.
*
* #see http://stackoverflow.com/questions/19940733/magento-translations-ok-in-online-program-but-not-run-as-cronjob#
* #param integer $storeId
* #param string $area
*
* #return string initial locale code
*/
protected function _emulateLocale($storeId, $area = Mage_Core_Model_App_Area::AREA_FRONTEND)
{
$initialLocaleCode = $this->_app->getLocale()->getLocaleCode();
$newLocaleCode = $this->_getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $storeId);
$this->_app
->getLocale()
->setLocaleCode($newLocaleCode);
$this->_factory
->getSingleton('core/translate')
->setLocale($newLocaleCode)
->init($area, true);
return $initialLocaleCode;
}
Magento 2
I guess the developers became aware it was borked and they changed the code in Magento 2. The _emulateLocale() function is gone all together and they added this line to the startEnvironmentEmulation() function, without any conditional around it:
$this->_localeResolver->setLocale($newLocaleCode);
It's a bug even with CE 1.9.0.1!
See what I've done about it:
https://magento.stackexchange.com/questions/25612/cron-job-template-block-not-being-translated-but-testobserver-is/25920#25920
I have a component that has a controller called MyproductControllerGeneralsetting which extends JControllerForm. Inside MyproductControllerGeneralsetting I am overwriting the save method from the parent class in order to modify $_POST data and then the overwriting method calls the parent class' save method to do the actual saving.
Here's the overwritten method in MyproductControllerGeneralsetting:
/**
* We overwrite the saved form data and trim them to avoid spaces
*/
public function save($key = null, $urlVar = null){
if($_POST['jform']){
foreach($_POST['jform'] as $key=>&$value){
$value = trim($value);
}
}
// Finally, save the processed form data (calls JControllerForm-save())
parent::save('id', $urlVar);
}
The thing is that even though I've trimmed each POST data field in this overwriting method, if I have some values submitted such as 'value ' (note the space in the end), they are not trimmed.
I've checked the save method of the JControllerForm class and it seems to be getting the data from POST here:
$data = $this->input->post->get('jform', array(), 'array');
Maybe that's the reason? Is this getting cached data or something?
Instead of trying to get the values from $_POST directly, try getting and setting the data in the same way the parent class does - using an internal pointer to a (shared) instance of the JInput class.
Here's a modified, working, overwritten save method:
/**
* We overwrite the saved form data and trim them to avoid spaces
*/
public function save($key = null, $urlVar = null){
if($_POST['jform']){
// Get the original POST data
$original = JRequest::getVar('jform', array(), 'post', 'array');
// Trim each of the fields
foreach($original as $key=>$value){
$original[$key] = trim($value);
}
// Save it back to the $_POST global variable
JRequest::setVar('jform', $postData, 'post');
}
// Finally, save the processed form data
return parent::save('id', $urlVar);
}
The controller is the wrong place for such things anyway, or is there a specific reason you want to do it in the controller?
Better look at the prepareTable function in the model. There you already have the table object with the properties to save and can sanitise them prior to saving.
Additional Info:
If you extend JControllerForm, you can specify
/**
* #since 1.6
*/
protected $view_item = 'item';
/**
* #since 1.6
*/
protected $view_list = 'items';
By default, the $view_item will equal to the context. The $view_list tries to guess a pluralized version of the $view_item. Usually by adding an s to the end.