繁体   English   中英

从其他函数访问变量-Symfony2

[英]Accessing Variables from other functions - Symfony2

新手问题提示...

好的,因此当前尝试将用户输入的值(质量)从他们希望使用的度量转换为Mg,然后将其存储在数据库中。

目前我有这个:

public function setUnit($unit)
{
    $this->unit = $unit;

    return $unit;
}
public function getUnit()
{
    return $this->unit;
}
public function setSize($size)
{
    $unit = $this->unit;

    $this->size = $size = new Mass($size, $unit);
    $this->size = $size->toUnit('mg');

    return $this;
 }

“新质量”功能是由TriplePoint创建的,用于从度量到度量的转换。

https://github.com/triplepoint/php-units-of-measure/

现在,如果我将$ unit变量显式设置为'grams'和'kg'或我选择的内容,它将进行转换,但是我不想强迫用户仅使用一种度量。 因此,我认为创建一个新变量$ unit并使用它的设置器/获取器,然后输入到unit框的文本将在newMass函数中被接受。 相反,我得到这个:

 Unknown unit of measure ($unit)

我认为这意味着它正在尝试使用“ $ this-> unit”作为变量,而不是文本字段中的文本。

就像我说的那样,我真的很陌生,对不起,如果我对此问题感到恼火,那就对不起。

一旦完成此操作,我希望为用户创建一个数组供我选择,不过我认为我可以自己进行管理。

编辑 -


public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('prod')
        ->add('product_code')
        ->add('size')
        ->add('cost')
        ->add('discount')
        ->add('foodcat')
        ->add('unit', 'choice', array(
'choices'   => array(
    'g'   => 'G',
    'kg' => 'Kg',
    'mg'   => 'Mg',
    'oz'   => 'Oz',
    'lb'   => 'Lb',
),
'multiple'  => false,
));        
}

这是我的表单的代码。

因此,我希望$ unit的值是从单位选择数组中选择的值。 这就是为什么我尝试使用以下方法加载它:

public function setSize($size)
{
    $unit = $this->unit;

尽管我认为这不是从“ public function setUnit”中获取设置变量的正确方法

编辑-

如果我做 :

        $unit = 'g';

    $this->size = $size = new Mass($size, $unit);
    $this->size = $size->toUnit('mg');

    return $this;

它工作得很好。

因此,实际上我只是在问..我如何访问setUnit方法中设置的变量?

错误消息Unknown unit of measure ($unit)为您提供了足够的信息。

在这一行: $this->size = $size = new Mass($size, $unit); ,则无法识别$unit

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM